简体   繁体   中英

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

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 , ie 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.

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM