如何推到一个MongoDB的阵列AngularJS? [英] How to push to a MongoDB array with AngularJS?

查看:162
本文介绍了如何推到一个MongoDB的阵列AngularJS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了一堆意见追加到MongoDB的阵列AngularJS的$ http服务,但我似乎已经进入了死胡同。这里是code我想(这坠毁我的DOM):

  $ scope.saveComment =功能(我){
      的console.log(ID为+ I);
      $ http.put('/ API /公司/+ I,{注释:{$推:{关键词:$ scope.comment,用户id:$ scope.getCurrentUser()名}}}).success(功能(东东){
         document.location.reload(真);
       })
    }

我试图用MongoDB的 $推的方法来做到这一点,但角度不会有它。任何线索,我怎么能做到这一点?

真诚的,

彼得

P.S。

下面是服务器端的code为特定型号的更新功能:

  //更新现有它在数据库中。
exports.update =功能(REQ,RES){
  如果(req.body._id){删除req.body._id; }
  It.findById(req.params.id,函数(ERR,吧){
    如果(ERR){返回的HandleError(RES,ERR); }
    如果{返回res.send(404)(它!); }
    VAR更新= _.merge(它,req.body);
    updated.save(功能(错误){
      如果(ERR){返回的HandleError(RES,ERR); }
      返回res.json(200,它);
    });
  });
};`


解决方案

有在这里几件事情是不是很大,但首先要支付的基本知识,让你去。

的第一件事是修复方法调用服务端角。该API端点当然不指望你正在使用MongoDB的更新的语法,而只是一个对象。因此,首先固定的:

  $ scope.saveComment =功能(我){
    的console.log(ID为+ I);    //这些拆分出来,使他们很容易日志和调试
    VAR路径='/ API /它的'+ I;    //这必须反映预期的文档中该元素的结构
    //因此,意见重新psented作为对象的数组$ P $,甚至
    //其中,这是唯一的一个。
    VAR数据= {
       注释: [{
         关键词:$ scope.comment,
         用户名:。$ scope.getCurrentUser()名
       }]
    };    //与响应呼叫服务
    $ http.put(路径数据).success(功能(东西){
      document.location.reload(真);
    });
}

现在您的服务器API端有一些缺点,我会preFER一个完全重新设计,但在缺乏信息的,只是集中在固定的主要问题,而不改变了。

假设这是 lodash 库时,的 .merge() 这里功能被错误地执行。它需要被告知如何处理中的合并正确,并且在present会发生是一个覆盖最好的数组的内容。所以,我们给它一些智慧:

  //更新现有它在数据库中。
exports.update =功能(REQ,RES){
  如果(req.body._id){删除req.body._id; }
  It.findById(req.params.id,函数(ERR,吧){
    如果(ERR){返回的HandleError(RES,ERR); }
    如果{返回res.send(404)(它!); }
    VAR更新= _.merge(它,req.body,功能(A,B){
        如果(_.isArray(一)){
            返回a.concat(B); //加入源和输入
        }
    });
    updated.save(功能(错误){
      如果(ERR){返回的HandleError(RES,ERR); }
      返回res.json(200,更新);
    });
  });
};`

但有一个渔获物,由于它只会追加到数组。所以,如果你把东西在你输入的是已经存在,那么无论是在数组输入原来的项目,任何将增加。

与处理是一个整体的另外一个问题需要解决,这取决于你的需求。

从我自己的角度探讨,我只想送数组,其中可能,有一个端点是仅仅为追加到文件的阵列,而不是因为你这里有通用文档更新。

这可以让你更好地利用MongoDB的更新功能,每预期的操作。因此,像这样的服务电话:

  //注释可以只是一个单一的对象现在
$ http.put(路径,{
    字:这一点,
    用户id:123
})。成功(功能(东西){

和对服务器API结束:

  exports.addComment =功能(REQ,RES){
  如果(req.body._id){删除req.body._id; }
  It.findByIdAndUpdate(req.params.id,
     {$推:{评论:req.body}},
     {新:真正},
     功能(ERR,吧){
      如果(ERR){返回的HandleError(RES,ERR); }
      如果{返回res.send(404)(它!); }
      返回res.json(200,它);
     }
  );
};

这样只会采取评论的身体,并追加到数组中。更重要的是它这个原子,这样就没有其他可能的请求可能在做类似目前的合并正在做碰撞。相同的端点将只是附加在当前状态阵列其他请求作为时提出要求,因此将这种

这是个什么 $推 经营人,所以它是明智的使用它。

有些耐人寻味。

I'm trying to append a bunch of comments to a MongoDB array with AngularJS's $http service, but I seem to have hit a dead end. Here is the code I tried (which crashed my 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);
       })
    }

I was trying to use MongoDB's $push method to do this, but Angular won't have it. Any clue as to how I could do this?

Sincerely,

Peter

P.S.

Here is the server-side code for that particular model's update functionality :

// 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);
    });
  });
};`

解决方案

There are a couple of things in here that are not great, but first to cover the basics and get you going.

The first thing is to fix the method calling the service angular side. The API endpoint certainly does not expect the MongoDB update syntax you are using, but rather just an object. So first fixing that:

$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);
    });
}

Now your server API end has some faults, I would prefer a total redesign, but in lack of info, just concentrating on fixing the main problems without changing much.

Assuming this is the lodash library, the .merge() function here is implemented incorrectly. It needs to be told how to "handle" the array content in the "merge" properly, and at present the best that will happen is an "overwrite". So we give it some smarts:

// 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);
    });
  });
};`

But there is a catch to that, as it will only "append" to the array. So if you put something in your input that was already there, then both the original items and anything in the array input would be added.

Dealing with that is a whole other issue to work out, depending on your needs.

From my own perpective, I would just send the array where possible and have an endpoint that is "just" for appending to the array of the document, rather than a "generic" document update as you have here.

This allows you to better utilize the MongoDB update functions, per expected actions. So something like this in the service call:

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

And on the server API end:

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);
     }
  );
};

So that will simply take the body of a "comment" and append it to the array. Most importantly it does this "atomically", so that no other possible request could collide in doing something like the current "merge" is doing. Other requests to the same endpoint will just "append" to the array in the current state as when the request is made, and so will this.

That is what the $push operator is for, so it's wise to use it.

Some food for thought.

这篇关于如何推到一个MongoDB的阵列AngularJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆