【问题标题】:How to update Document in MongoDB via Node.js and Angular.js如何通过 Node.js 和 Angular.js 更新 MongoDB 中的文档
【发布时间】:2015-07-22 22:25:50
【问题描述】:

我在 MongoDb 中的文档如下所示:

{
    "_id" : ObjectId("5550e710dad47584cbfe9da1"),
    "name" : "Serverraum1",
    "tables" : [
                  {
                    "name" : "Table1",
                    "nummer" : "1",
                    "reihe" : "2",
                   }
               ]
}

发布方式:

app.post('/serverraeume', function (req, res) {
    console.log(req.body);
    db.serverraeume.update(req.body, function (req, res) {
    });
});

还有 Angular 控制器中的 http 帖子:

$scope.addSchrank = function (serverraum){  
    $http.post('/serverraeume', $scope.table);
}

我想在 Document Serverraum1 表中进行更新。如何在表格中推送 $scope.table?

【问题讨论】:

  • console.log(req.body)登录的对象是什么?
  • 例如:{ name: 'Test', number: '2', row: '2' }

标签: javascript angularjs node.js mongodb


【解决方案1】:

要通过推送$scope.table 来更新文档serverraum1 表中,mongodb update 函数您的POST 方法应该使用$addToSet 运算符,该运算符将值添加到数组,除非value 已经存在,在这种情况下 $addToSet 对该数组没有任何作用:

app.post('/serverraeume', function (req, res) {
    console.log(req.body);
    var query = {"name" : "Serverraum1"}, // the query object to find records that need to be updated
        update = { "$addToSet": { "tables": req.body } }, // the replacement object
        options = {}; // defines the behaviour of the function
    db.serverraeume.update(query, update, options, function (req, res) {
        console.log(res);
    });
});

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 2014-10-31
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2011-12-04
    • 2017-06-21
    • 1970-01-01
    相关资源
    最近更新 更多