繁体   English   中英

如何使用AngularJS推送到MongoDB数组?

[英]How to push to a MongoDB array with AngularJS?

我正在尝试使用AngularJS的$ http服务向MongoDB数组添加一堆注释,但是我似乎陷入了死胡同。 这是我尝试的代码(使我的DOM崩溃):

$scope.saveComment = function(i){
      console.log("id is " + i);
      $http.put('/api/its/' + i, { comments: {$push: { words: $scope.comment, userId: $scope.getCurrentUser().name } } } ).success(function(stuff){
         document.location.reload(true);
       })
    }

我试图使用MongoDB的$push方法来做到这一点,但是Angular却没有。 关于我该怎么做的任何线索?

此致

彼得

PS

这是该特定模型的更新功能的服务器端代码:

// Updates an existing it in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  It.findById(req.params.id, function (err, it) {
    if (err) { return handleError(res, err); }
    if(!it) { return res.send(404); }
    var updated = _.merge(it, req.body);
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, it);
    });
  });
};`

这里有几件不好的事情,但是首先要涵盖基础知识并帮助您入门。

第一件事是修复调用服务角度侧的方法。 API终结点当然不希望您使用的是MongoDB更新语法,而只是一个对象。 因此,首先解决该问题:

$scope.saveComment = function(i){
    console.log("id is " + i);

    // Split these out so they are easy to log and debug
    var path = '/api/its' + i;

    // This must mirror the structure expected in your document for the element
    // Therefore "comments" is represented as an array of objects, even
    // where this is only one.
    var data = { 
       comments: [{ 
         words: $scope.comment,
         userId: $scope.getCurrentUser().name 
       }]
    };

    // Call service with response
    $http.put(path,data).success(function(stuff){
      document.location.reload(true);
    });
}

现在您的服务器API端出现了一些故障,我希望进行全面的重新设计,但是由于缺乏信息,所以只专注于解决主要问题而不进行太多更改。

假设这是lodash库,则此处的.merge()函数未正确实现。 需要告诉我们如何正确“处理”“合并”中的数组内容,目前最好的做法是“覆盖”。 因此,我们给了它一些技巧:

// Updates an existing it in the DB.
exports.update = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  It.findById(req.params.id, function (err, it) {
    if (err) { return handleError(res, err); }
    if(!it) { return res.send(404); }
    var updated = _.merge(it, req.body,function(a,b) {
        if (_.isArray(a)) {
            return a.concat(b);    // join source and input
        }
    });
    updated.save(function (err) {
      if (err) { return handleError(res, err); }
      return res.json(200, updated);
    });
  });
};`

但是有一个陷阱,因为它只会“附加”到数组中。 因此,如果您在输入中添加了已经存在的内容,那么原始项目和数组输入中的任何内容都将被添加。

根据您的需要,解决该问题是另一个完全问题。

从我自己的角度来看,我只会在可能的情况下发送该数组,并具有一个“正好”用于附加到文档数组的终结点,而不是像在此处那样对“通用”文档进行更新。

这样,您可以按照预期的操作更好地利用MongoDB更新功能。 所以在服务调用中是这样的:

// comment can just be a singular object now
$http.put(path,{ 
    "words": "this that", 
    "userId": 123
}).success(function(stuff){

在服务器API端:

exports.addComment = function(req, res) {
  if(req.body._id) { delete req.body._id; }
  It.findByIdAndUpdate(req.params.id,
     { "$push": { "comments": req.body } },
     { "new": true },
     function(err,it) {
      if (err) { return handleError(res, err); }
      if(!it) { return res.send(404); }
      return res.json(200, it);
     }
  );
};

这样就可以简单地将“注释”的主体添加到数组中。 最重要的是,它“原子地”执行此操作,因此在执行当前“合并”操作时,其他任何可能的请求都不会发生冲突。 发出相同请求时,对同一端点的其他请求将仅在当前状态下“追加”到数组,因此也是如此。

这就是$push运算符的用途,因此使用它是明智的。

一些思考的食物。

暂无
暂无

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

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