【问题标题】:Delete 'note' in collection from mongoDB in Node.js Express从 Node.js Express 的 mongoDB 中删除集合中的“note”
【发布时间】:2016-12-27 00:05:26
【问题描述】:

我想知道如何在 Node.js 中从我的 mongoDB 中删除“注释”

我是 Node.js、Express 和 mongoDB 的新手。

我将在这里展示我的代码,并让它自己说话......

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:

     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:这是我要删除的注释。不是编程,因为那是类别。

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

我在测试时使用 Fiddler,我得到 200 作为状态码...但它不会从数据库中删除。请帮忙! :)

提前致谢:)

【问题讨论】:

  • 如果我理解正确,那么您只想删除数组中的元素而不是整个文档,对吗?
  • 是的,完全正确 :) 抱歉,如果我不清楚@DAXaholic

标签: javascript angularjs node.js mongodb api


【解决方案1】:

我认为不是

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

您应该将update$pull 一起使用,即类似这样的东西

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

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

请参阅以下 GIF,它说明了您的示例文档。
当然,您必须确保从请求数据中正确设置了 note

【讨论】:

  • 谢谢!效果很好!还有一件事。在客户端我有这个角代码: $scope.removeNote = function(note) { $http.put(notesUrl + '/'+ note) .then(function (result) { $scope.notes = result.data; } , 功能(错误){ 控制台.log(错误); }); };
  • 它可以工作,但在页面上看起来很奇怪,所以我必须刷新它。插入一个新的时我有类似的情况当我插入一个新的时,注释显示没有页面刷新。也有可能在这里实现吗? @DAXaholic
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
  • 2012-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多