I have notes nested in userSchema I am trying to delete one object by _id but deleteOne is removing the whole user object so how can I can delete the one with _id
const keeperSchema = mongoose.Schema({
noteName:String,
noteContent:String,
})
const userSchema = mongoose.Schema({
email:String,
password:String,
notes:[keeperSchema]
})
app.post("/delete",(req,res)=>{
const id=req.body.id
const email=req.body.email
console.log(id)
Keeper.deleteOne({"notes._id":id}).then(()=>{
Keeper.find({email:email},(err,results)=>{
if(results){
console.log(results)
}
})
})
})
CodePudding user response:
you can do it like so:
userModel.updateOne({_id: idofUser}, {$pull: {notes: {_id: idofnote}}})
you should query on your userModel
because you want to pull an element from keeper array which is stored in user
so you have to determine from which user you want to delete your note thats why you need to have the id of user. if you want to delete a specific note from all of the users just clear your condition like so:
userModel.updateMany({}, {$pull: {notes: {_id: idofnote}}})