Abban Fahim
Abban Fahim

Reputation: 1

Finding an particular document inside an array

So I have an app which has a collection of users and it stores notes for each particular user inside an array:

My collection of users

The array of notes of one person

If I have the id of the note and the user to whom the note belongs to, how can i query for that specific note and ($pull/delete) it. I have tried to find the correct query for it but to no avail:

app.get('/delete/:userId/:noteId', (req,res)=>{
let noteId = req.params.noteId;
User.findOne({'notes': {_id: noteId}},(err,foundNote)=>{
    console.log(foundNote);
});

});

What I am looking for is a the condition I need to set for finding that particular note document. Thank you in advance :).

Upvotes: 0

Views: 29

Answers (2)

Amir BenAmara
Amir BenAmara

Reputation: 686

you can use $pull :

app.get('/delete/:userId/:noteId', (req,res)=>{
   let noteId = req.params.noteId;
   let userId= req.params.userId;
   User.findByIdAndUpdate(userId, { $pull: { notes: noteId  })
})

Upvotes: 1

A S M.Abdur Rab
A S M.Abdur Rab

Reputation: 46

Use ObjectId, your filter will be:

{ 'notes._id': ObjectId(noteId) }

Upvotes: 0

Related Questions