2015-06-02 14 views
2

我喜歡這個 -如何在模式中動態添加對象?

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,甚至更多的測試,我該如何實現這一目標?

回答

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 
}) 
+0

我要動態地添加在反應領域和資源領域的物體也可能是兩個以上。如何以一般化的方式做到這一點? –

+0

@NitishKumar你可以編輯你的問題,幷包括一些例子?你提到你希望如何更新響應密鑰,並在上面提供了這一點。如果您需要動態創建更新對象,則可以使用[**括號符號**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators)來設置對象/ Property_Accessors)。 – chridam

+0

我想在以下步驟中更新文檔 - 1)響應:{} 2)響應:{test123:{},res:{}} 3)響應:{test123:{dur:30,refresh: false},res:{{key1:val1}}} 4)response:{test123:{dur:30,refresh:false},res {{key1:val1},key2:val2}} simillarly我想添加test456和甚至更多的測試 –