使用nodejs/mongoose部分更新子文档 [英] Partial update of a subdocument with nodejs/mongoose

查看:381
本文介绍了使用nodejs/mongoose部分更新子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to set multiple properties on a (sub)document in one go with Mongoose? An example of what I'm trying to do:

比方说我有这个模式:

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的子文档(嵌入式架构).所以当我尝试做

Normally, I could achieve this using the $set operator, but my problem is that document in this example is a subdocument (embedded schema) of parentDoc. So when I tried to do

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

它替换了subDocs._id标识的子文档实例.目前,我已经通过手动设置仅字段来解决"了该问题,但我希望有一种更好的方法.

it replaced the subdocument instance identified by subDocs._id. Currently I have "solved" it by setting only fields manually, but I was hoping for a better way to do this.

推荐答案

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

Build up a $set object programmatically based on the fields of partialUpdate to update just those fields using dot notation:

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

这篇关于使用nodejs/mongoose部分更新子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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