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

Time:09-19

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

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..

CodePudding user response:

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.

  • Related