我有这样的收藏-

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甚至更多测试,如何实现呢?

最佳答案

$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
})

关于node.js - 如何在架构中动态添加对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30603803/

10-13 01:59