node.js - How to dynamically add an object in schema? -
i have collection this-
var schema= new mongoose.schema({ username:{type:string}, responses:{type:mongoose.schema.types.mixed} });
i save document in collection like-
{ username:anonymous,responses:{}}
now want update -
{username:anonymous,responses:{tst123:{duration:30,res:{}},tet456:{duration:50,res:{}}}
i want update document in following step goes-
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} }
similarly, want add test456
, more tests, how achieve this?
use $set
operator in update method follows:
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 number of updated documents })
Comments
Post a Comment