I am using React and Nodejs to build a note website. The npm packages I am using are:
- express-session
- passport
- passport-local
- passport-local-mongoose
My user schema looks like this-
{
"_id" : ObjectId("6267e8f8502e789211229a38"),
"username" : "[email protected]",
"notes" : [
{
"date" : "26 Apr",
"title" : "Lorem ipsum is placeholder text",
"content" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut ",
"_id" : ObjectId("6267e95a502e789211229a45")
},
{
"date" : "26 Apr",
"title" : "Lorem ipsum is placeholder text",
"content" : "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut ",
"_id" : ObjectId("6267e96b502e789211229a54")
}
],
"folders" : [],
"salt" : "......",
"hash" : "......",
"__v" : NumberInt(2)
}
My problem is I can't delete a single note located inside the User data of the user who is logged In. I know how to delete a model but I don't know how to only delete specific files located inside that model.
My goal is to delete one note inside the notes array.
Can anyone help?
CodePudding user response:
You can do the following, which pulls the note using noteId
from the notes array. You need the noteId either from params or from req.body
router.delete('/:userId/notes/:noteId', async (req, res) => {
try {
const user = await User.updateOne(
{ _id: req.params.userId },
{ $pull: { notes: { _id: req.params.noteId } } }
res.send(user);
);
} catch (err) {
res.status(500).send(err);
}
})