0

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)
           }
        })
    })

   })

1 Answer 1

1

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}}})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.