I want to delete an element according to the value of "noteID" from the note array inside the project schema in mongo db.
Project Schema
endDate: {
type: String,
required: true,
default: Date.now().toString()
},
notes: {
type: [NoteSchema],
required: false
},
users: [{
type: String,
required: false
}]
Note Schema
const NoteSchema = mongoose.Schema({
noteID: {
type: String,
require: true
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
endDate: {
type: Date,
default: Date.now()
},
priority: {
type: String,
default: "low"
}
});
returning json with express
"endDate": "11.11.2021",
"notes": [
{
"endDate": "2022-02-05T08:02:18.166Z",
"priority": "low",
"_id": "61fe2f423667ad054b62f84f",
"noteID": "cb978ec0-7229-4253-9e36-eaaf85b72ae3",
"title": "test note title",
"description": "test note desc"
},
{
"endDate": "2022-02-05T08:02:18.166Z",
"priority": "medium",
"_id": "61fe2f593667ad054b62f851",
"noteID": "760fda9f-e453-4e9c-bc9f-161f38fd29c0",
"title": "test note title 2",
"description": "test note desc 2"
}
],
"users": [],
I want to delete an item from this notes directory using noteID.
CodePudding user response:
Basically you can delete a schema item like that in mongoose.
YourColletionName.findOneAndDelete({ noteID: "cb978ec0-7229-4253-9e36-eaaf85b72ae3" },
function (err, data) {
if (err){
console.log(err)
}
else{
console.log("Removed: ", data);
}
});
If you want to delete with the noteID link on your page you can use req.params.noteID instead of cb978ec0-7229-4253-9e36-eaaf85b72ae3.
Resources:
- https://www.geeksforgeeks.org/mongoose-findoneandremove-function/
- https://mongoosejs.com/docs/api.html#model_Model.findOneAndDelete
CodePudding user response:
Use update with $pull to remove the element from the array by noteID:
db.collection.update({},
{
$pull: {
notes: {
noteID: "cb978ec0-7229-4253-9e36-eaaf85b72ae3"
}
}
})
Explained:
The above query will remove all objects with nodeID: "cb978ec0-7229-4253-9e36-eaaf85b72ae3" from the array of objects notes[]. The operation apply to the first found document in collection. If you need to apply to all documents in collections you need to add the { multi:true } option
