Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongoose findById() – Not Working, Tried all the functions to get document by ID, None of them works

Mongoose findById not working.
It only works when i call just Course.find();

Here’s my code

const mongoose = require("mongoose");
mongoose
  .connect("mongodb://localhost/mongo-exercises")
  .then(() => console.log("Connected to MongoDB"))
  .catch((err) => console.error("Could not connect to MongoDB", err));

  const courseSchema = mongoose.Schema({
  tags: [String],
  date: { type: Date, default: Date.now },
  name: String,
  author: String,
  isPublished: Boolean,
  price: Number,
});

const Course = mongoose.model("Course", courseSchema);

async function updateCourse(id){
    const course = await Course.findById(id);
    if(!course) return ;
    console.log(course);
    course.isPublished = true;
    course.author = "Changed Author";
    
    const result = await course.save();
    
    console.log(result);
}
async function getCourses() {
    const courses = await Course.find();
    console.log(courses);
}
updateCourse('5a68fdd7bee8ea64649c2777');

These are all the documents i have none of them can be changed

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My VSCODE terminal shows this response

anuragtj@Anurags-MacBook-Pro exercise % node index.js           
Connected to MongoDB

It just stops at connected to mongodb shows nothing else.

I tried multiple ways of getting document byiD none of them works , and i think its a problem in my db, because none of the methods are working..

>Solution :

Your database is showing that the _id fields are stored as type String, but your schema doesn’t reflect that (which means that Mongoose will assume that _id is of type ObjectId, and will convert it to that type before making a query).

If you add _id to your schema the queries will start working:

const courseSchema = mongoose.Schema({
  _id : String,
  ...
});

However, I would suggest fixing the main issue, namely a schema mismatch between the code writing to the database and this code that’s querying the database.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading