简体   繁体   English

从Node.js Express中的mongoDB中删除集合中的'note'

[英]Delete 'note' in collection from mongoDB in Node.js Express

I wonder how to delete a 'note' from my mongoDB in Node.js 我想知道如何从Node.js中的mongoDB中删除'note'

I'm new to Node.js, Express and mongoDB. 我是Node.js,Express和mongoDB的新手。

I'll just show my code here and let that speak for it self... 我只是在这里展示我的代码并让它代表自己......

notesController.js: 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.js来自数据文件夹:

     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. MongoDB:这是我试图删除的注释。 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. 我在测试时使用Fiddler,我得到200作为状态代码...但它不会从数据库中删除。 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 你应该使用$ pull update ,即类似这样的东西

...
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. 请参阅以下GIF,其中说明了您的示例文档。
Of course you will have to make sure that note is correctly set from the request data. 当然,您必须确保从请求数据中正确设置了note

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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