Sunday, May 23, 2021

Updating a Document

  //Approach: Query first

 //findById()

 //Modify the properties

 //save()

async function updateCourse(id){

 const course = await Course.findById(id);
 if(!course) return;
 course.isPublished = true;
 course.author = 'Another Author';
 //can set individual properties like above or like below whole object.
 /*course.set({
  isPublished: true,
  author: 'Another Author'
 })*/

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


}

updateCourse("<id_of_a_course>");

 //Approach: Update first

 //Update directly

 //Optionally: get the updated document


async function updateCourse(id){

 const result = await Course.update({_id: id},
{
 $set:{
  author: 'Mosh',
  isPublished: false
 }
}
);
 
console.log(result);

}

updateCourse("<id_of_a_course>");

//below will return course object instead of the status code,but the original document, not the updated one.
async function updateCourse(id){

 const course = await Course.findByIdAndUpdate(id,
{
 $set:{
  author: 'Jack',
  isPublished: false
 }
}
);
 
console.log(course);

}

updateCourse("<id_of_a_course>");

//To get the updated object as result.

 const course = await Course.findByIdAndUpdate(id,
{
 $set:{
  author: 'Jason',
  isPublished: false
 }
},{new: true}
);

https://docs.mongodb.com/manual/reference/operator/update/

No comments:

Post a Comment