如何在架构中动态添加对象?

时间:2015-06-02 18:29:01

标签: node.js mongodb mongoose

我有一个这样的集合 -

var schema= new mongoose.Schema({
  username:{type:String},
  responses:{type:mongoose.Schema.Types.Mixed}
});

我将文档保存在集合中 -

{ username:anonymous,responses:{}}

现在我希望将其更新为 -

{username:anonymous,responses:{tst123:{duration:30,res:{}},tet456:{duration:50,res:{}}} 

我希望在以下步骤中更新文档 -

1)responses:{}

2)responses:{test123:{},res:{}}

3)responses:{test123:{dur:30,refresh:false},res:{{key1:val1}} }

4)responses:{ test123:{dur:30,refresh:false},res {{key1:val1},key2:val2} }

同样,我想添加test456甚至更多测试,我该如何实现?

1 个答案:

答案 0 :(得分:0)

使用 $set 方法中的update运算符,如下所示:

var schema= new mongoose.Schema({
    username: { type: String },
    responses: { type: mongoose.Schema.Types.Mixed }
});

var Thing = mongoose.model('Thing', schema),
    query = { 'username': 'anonymous' },
    update = { 
        '$set': { 
            'responses': {
                'tst123': {
                    'duration': 30,
                    'res': {}
                },
                'tet456': {
                    'duration': 50,
                    'res': {}
                } 
            }
        }
    },
    options = { multi: true };

Thing.update(query, update, options, callback);

function callback (err, numAffected) {
  // numAffected is the number of updated documents
})