oOMelon oOMelon - 3 months ago 9
Node.js Question

Delete 'note' in collection from mongoDB in Node.js Express

I wonder how to delete a 'note' from my mongoDB in Node.js

I'm new to Node.js, Express and mongoDB.

I'll just show my code here and let that speak for it self...

notesController.js:

app.delete('/api/notes/:categoryName/:note',
// auth.ensureApiAuthenticated, commented when testing.
function(req, res) {

var categoryName = req.params.categoryName;
var note = req.params.note;

data.removeNote(categoryName, note, function(err, notes){
if(err) {
res.send(400, err);
}
else {
res.send(200);
}
});
});


index.js from data folder:

data.removeNote = function(categoryName, note, next) {
database.getDb(function(err, db){
if(err) {
next(err);
}
else {
db.notes.remove({ note: note }, function(err, results) {
console.log(results); //not too sure what to do here?
next();
});
}
});
};


MongoDB: This is the note I'm trying to delete. Not Programming since that's the category.

{
"name": "Programming",
"notes": [
{
"note": "Fiddler Note",
"color": "blue",
"author": "oOMelon"
}
]
}


I use Fiddler when testing and I get 200 as status code... But it doesn't get deleted from the DB. Please help! :)

Thanks in advance :)

Answer

I think instead of

...
db.notes.remove({ note: note }, function(err, results) {
    console.log(results); //not too sure what to do here?
    next();
});
...

you should rather use an update with $pull, i.e. something like this

...
db.notes.update({ "notes.note": note }, 
                { $pull: { notes: { note: note } } }, 
                function(err, results) {

    console.log(results); //not too sure what to do here?
    next();
});
...

see the following GIF which illustrates that for your sample document.
Of course you will have to make sure that note is correctly set from the request data.

enter image description here

Comments