在Mongoose中更新非常嵌套的文档

时间:2016-07-21 00:24:16

标签: javascript node.js mongodb mongoose

如果给出以下架构,我如何更新array1.array2.status

var SomeSchema = new mongoose.Schema({
    status: Boolean, 
    array1: [{
        array2[{
            status: boolean
        }]
    }]
})

1 个答案:

答案 0 :(得分:0)

首先,将Schema重组为SubSchema会很好:

var valueItemSchema = new mongoose.Schema({
    _id: Number,
    status: Boolean
});

var subItemSchema = new mongoose.Schema({
    _id: Number,
    array2: [valueItemSchema]
});

/*
//or this if you dont want _id in your nested documents

var valueItemSchema = new mongoose.Schema({
    status: Boolean
}, {
    _id: false
});

var subItemSchema = new mongoose.Schema({
    array2: [valueItemSchema]
}, {
    _id: false
});
*/

var itemSchema = new mongoose.Schema({
    status: Boolean,
    array1: [subItemSchema]
});

var valueItem = db.model('ValueItem', valueItemSchema);
var SubItem = db.model('SubItem', subItemSchema);
var Item = db.model('Item', itemSchema);

//create a new item
var myItem = new Item({
    status: true,
    array1: new SubItem({
        _id: 0,
        array2: [new valueItem({
            _id: 0,
            "status": true
        }), new valueItem({
            _id: 1,
            "status": false
        }), new valueItem({
            _id: 2,
            "status": true
        })]
    })
});

然后,您可以array2更新_id的元素:

Item.findOne({
    status: true
}).exec(
    function(err, result) {
        result.array1.id(0).array2.id(0).status=false;
        result.save(function(err) {
            console.log(result)
        });
    }
);

或者,如果您不希望子文档中的任何_id按索引更新:

Item.findOne({
    status: true
}).exec(
    function(err, result) {

        result.array1[0].array2[0].status=false;
        result.save(function(err) {
            console.log(result)
        });
    }
);

Here是一个完整的演示