CRUD
Query first approach
const updateCourse = async(id) =>{
const course = await Course.findById(id);
if(!course) return;
couse.isPublished = false;
course.author = "Michael";
const result = await course.save();
console.log(result);
}
updateCourse('123456798asdf');
Update first approach
//method 1
const updateCourse = async(id) =>{
const result = await Course.update({_id:id},{$set:{author:"Michael",isPublished:false});
console.log(result);
}
//method 2
const updateCourse = async(id) =>{
const result = await Course.findByIdAndUpdate(id,{$set:{author:"Michael",isPublished:false},{new:true}); //new set to true will get the updated document
console.log(result);
}
//method 3
const updateCourse = async(id) =>{
const result = await Course.updateOne({_id:id},{$set:{author:"Michael",isPublished:false},{new:true});
console.log(result);
}
updateCourse('123456798asdf');
Update by passing in a new object
const updateCourse = async(id,obj) =>{
const course = await Course.findById(id);
if(!course) return;
course.set(obj); //this will replace only fields that is specified in the object
const result = await course.save();
console.log(result);
}
updateCourse('123456798asdf',{author:"Michael",isPublished:false});
Remove one Document
const removeCourse = async(id) =>{
const result = await Course.deleteOne({_id:id});
console.log(result);
}
removeCourse('123456798asdf');
//method 2: can get the removed document
const removeCourses = async(id) =>{
const result = await Course.findByIdAndRemove({isPublished:cond});
console.log(result);
}
removeCourse('123456798asdf');
Remove Many Documents
//will return the number of deleted documents
const removeCourses = async(cond) =>{
const result = await Course.deleteMany({isPublished:cond});
console.log(result);
}
removeCourses(false);