Mongoose - 搜索文档并更新子文档的某些字段

时间:2016-10-25 10:02:32

标签: javascript node.js mongoose

我对Mongoose很新,我正在努力熟悉它,但是糟糕的文档没有帮助(没有搜索,没有功能列表......)。

我有一个代表公司的文档,以及代表用户的子文档:

{
    "_id": "57ffa47f5b70f90831212348",
    "name": "mycompany",
    "address": "...",
    "phone": "...",
    "users": [
        {
            "_id": "57ffa47f5b70f90831212347",
            "username": "alpha",
            "name": "myname",
            "surname": "mysurname",
            "password": "..."
        }
    ]
}

我想找到一个特定的子文档,只更新从前端传递的一些字段(name,surname,password,...)。

我收到req.body,其中包含已修改的字段(即req.body.name)和包含已记录用户的req.user

"company_shortname": "CMPNY",
    "company_id": "57ffa47f5b70f90831212348",
    "user": {
        "id_access_level": 0,
        "surname": "ltd",
        "name": "mycompany",
        "username": "mycompanyusername",
        "_id": "57ffa47f5b70f90831212347",
        "password": "..."
    }
}

我想要获得的是找到已编辑的subdoc(包含此subdoc的公司将始终与登录的用户相同),更新传递的数据并保存。

使用此answer,我尝试了:

Company.find({'_id': req.user.company_id}).select('name').exec(
        function(err, company) {

          if (err) res.status(500).send(err);

          var partialUpdate = req.body;

          var set = {};
          for (var field in partialUpdate) {
          set['users.$.' + field] = partialUpdate[field];
          }

          company.update({_id: req.user._id, "users._id": req.body._id},
          {$set: set},
          function(err, numAffected) {
            console.log('Number of users edited: ' +JSON.stringify(numAffected,null,4));
          });
      });

但是我无法让它发挥作用..任何想法?

1 个答案:

答案 0 :(得分:0)

我使用此查询解决了:

//saving in 'set' the fields to be edited
var partialUpdate = req.body;
    var set = {};
    for (var field in partialUpdate) {
    set['users.$.' + field] = partialUpdate[field];
    }

    //find the company,then the subdoc, then set the fields with 'set'
    Company.findOneAndUpdate({
      '_id': req.user.company_id, "users._id" : req.body._id},
      {$set: set},
      function(err, company) {
        //the company status after the update
        console.log('company updated: ' +JSON.stringify(company,null,4));
      });