Mongoose Model.update not working in my code

Viewed 1835

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.

5 Answers

I don't see any issues in the code and here the query and syntax are correct, according to the MongoDB update doc.

The update() method returns a WriteResult object that contains the status of the operation. Upon success, the WriteResult object contains the number of documents that matched the query condition, the number of documents inserted by the update, and the number of documents modified.

Here no documents have been modified and the only reason is, you are setting the same data to update in the query.

Try using

isPublished: {
    type: Boolean,
    default: false
}

instead of

isPublished: Boolean

The return {ok: 1, nModified: 0, n: 0} says that the operation was successful but couldn't find, nor update any entry, so that means it's not even matching.

I'm not entirely sure, but I think mongoose only finds ID by ObjectId and not by string.

So you should get the desired outcome by converting it, like that:

const result = await Course.update({ _id: mongoose.Types.ObjectId(id) }, { 
    $set: { author: 'New', isPublished: false }
});

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.

add _id:String in your schema

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

And replace your promise with this:

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

I encountered the same problem in mosh node.js course and this solution worked for me! :)

Related