使用nodejs / mongoose部分更新子文档

时间:2013-04-08 08:41:22

标签: node.js mongodb mongoose

是否可以使用Mongoose一次性在(子)文档上设置多个属性?我正在尝试做的一个例子:

假设我有这个架构:

var subSchema = new Schema({
    someField: String,
    someOtherField: String
});

var parentSchema = new Schema({
    fieldOne: String,
    subDocs: [subSchema]
})

然后我想做:

exports.updateMyDocument = function(req, res) {
    var parentDoc = req.parentDoc; // The parent document. Set by parameter resolver.
    var document = req.myDoc; // Sub document of parent. Set by parameter resolver.
    var partialUpdate = req.body; // updated fields sent as json and parsed by body parser
    // I know that the statement below doesn't work, it's just an example of what I would like to do.
    // Updating only the fields supplied in "partialUpdate" on the document
    document.update(partialUpdate); 
    parentDoc.save(function(err) {
        if(err) {
            res.send(500);
            return;
        }
        res.send(204);
    }); 
};

通常,我可以使用$set运算符实现此目的,但我的问题是此示例中的documentparentDoc的子文档(嵌入式架构)。所以,当我试图做

Parent.update({_id: parentDoc._id, "subDocs._id": document._id}, 
    {$set: {"subDocs.$" : partialUpdate}}, 
    function(err, numAffected) {});

它替换了subDocs._id标识的子文档实例。目前我通过手动设置字段来“解决”它,但我希望有更好的方法来做到这一点。

4 个答案:

答案 0 :(得分:32)

根据$set的字段以编程方式构建partialUpdate对象,使用点表示法更新这些字段:

var set = {};
for (var field in partialUpdate) {
  set['subDocs.$.' + field] = partialUpdate[field];
}
Parent.update({_id: parentDoc._id, "subDocs._id": document._id}, 
    {$set: set}, 
    function(err, numAffected) {});

答案 1 :(得分:6)

我在REST应用程序中做了不同的事。

首先,我有这条路线:

router.put('/:id/:resource/:resourceId', function(req, res, next) {
    // this method is only for Array of resources.
    updateSet(req.params.id, req.params.resource, req, res, next);
});

updateSet()方法

function updateSet(id, resource, req, res, next) {
    var data = req.body;
    var resourceId = req.params.resourceId;

    Collection.findById(id, function(err, collection) {
        if (err) {
            rest.response(req, res, err);
        } else {
            var subdoc = collection[resource].id(resourceId);

            // set the data for each key
            _.each(data, function(d, k) {
              subdoc[k] = d;
            });

            collection.save(function (err, docs) {
              rest.response(req, res, err, docs);
            });
        }
    });
}

如果您为此子文档定义data,那么很棒的部分是mongoose将验证Schema。此代码对于作为Array的文档的任何资源都有效。为简单起见,我没有显示所有数据,但检查这种情况并正确处理响应错误是一种很好的做法。

答案 2 :(得分:1)

您可以分配或扩展嵌入文档。

    Doc.findOne({ _id: docId })
    .then(function (doc) {
      if (null === doc) {
        throw new Error('Document not found');
      }

      return doc.embeded.id(ObjectId(embeddedId));
    })
    .then(function(embeddedDoc) {
      if (null === embeddedDoc) {
        throw new Error('Embedded document not found');
      }

      Object.assign(embeddedDoc, updateData));
      return embeddedDoc.parent().save();
    })
    .catch(function (err) {
      //Do something
    });

在这种情况下,你应该避免_id没有分配。

答案 3 :(得分:0)

我在不使用$ set对象的情况下以稍微不同的方式处理了这个问题。我的方法类似于Guilherme,但一个区别是我将我的方法包装到静态功能中,以便在整个应用程序中更容易重用。示例如下。

在CollectionSchema.js服务器模型中。

collectionSchema.statics.decrementsubdocScoreById = function decreasesubdoc (collectionId, subdocId, callback) {
  this.findById(collectionId, function(err, collection) {
    if (err) console.log("error finding collection");
    else {
      var subdoc = collection.subdocs.filter(function (subdoc) {
        return subdoc._id.equals(subdocId);
      })[0];

      subdoc.score -= 1;

      collection.save(callback);
    }
  });
};

在服务器控制器中

Collection.decrementsubdocScoreById(collectionId, subdocId, function  (err, data) {
  handleError(err);
  doStuffWith(data);
});
相关问题