node.jsdatabasemongodbmongoosebackend

Mongoose Model.update not working in my code


I want to update some of the course properties with the given id. This is my code:

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

const Course = mongoose.model('Course', courseSchema);
mongoose.connect('mongodb://localhost/mongo-exercises');

async function updateCourse(id) {
     const result = await Course.update({_id: id}, {
        $set: {
            author: 'New', 
            isPublished: false
        }
    });

console.log(result);
}

updateCourse('5a68fde3f09ad7646ddec17e');

On console I get {ok: 1, nModified: 0, n: 0}.

I´ve tried updating the element with this other way, but it doesnt works. For this piece of code i dont get the result, no response:

const course = await Course.findById(id);
  if(!course) return; 

  course.isPublished = true; 
  course.author = 'Another Author';

  const result = await course.save();
  console.log(result);

When i try to update using the findByIdAndUpdate with this other code, the result is null in console:

 async function updateCourse(id) {
    const course = await Course.findByIdAndUpdate(id, {
    $set: {
        author: 'Billy',
        isPublished: false
    }
 });

   console.log(course);

 }
updateCourse('5a68fde3f09ad7646ddec17e');

The database im working with has:

 { _id: 5a68fdd7bee8ea64649c2777,
   name: 'Node.js Course',
   author: 'Sam',
   isPublished: true,
   price: 20 },
 { _id: 5a68fde3f09ad7646ddec17e,
   name: 'ASP.NET MVC Course',
   author: 'Mosh',
   isPublished: true,
   price: 15 },
 { _id: 5a6900fff467be65019a9001,
   name: 'Angular Course',
   author: 'Mosh',
   isPublished: true,
   price: 15 },
 { _id: 5a68fe2142ae6a6482c4c9cb,
   name: 'Node.js Course by Jack',
   author: 'Jack',
   isPublished: true,
   price: 12 }

The course doesn't update. Where is the error? Note that if i want to create new documents, it does it with no problem.


Solution

  • update({_id: id},...) specifies _id expecting the _id type in the document as ObjectID.

    update(), and findById(), do not find _id, and return null, because the _id type is, probably, String in your collection/document, - check with Compass.