node.js - Nodejs Mongo insert into subdocument - dynamic fieldname -
{username:'me', companies:{"yourcompany":{...}}
i want insert company user record (user collection), make:
{username:'me', companies:{ "yourcompany":{...}, "mycompany":{...} }
but name dynamic..
var companyid = "mycompany"; .collection('users').findandmodify( {username: usern}, [['_id', 'asc']], {$set:{companies:{companyid: { desksmemberships:[] }}}}, {new: true}, function(){...} gives this.. {username:'me', companies:{ "yourcompany":{...}, "companyid":{...} }
how do this?
you'd have build $set modifier programmatically:
var modifier = { $set: {} }; modifier.$set['companies.' + companyid] = { desksmemberships:[] }; and use modifier third parameter in findandmodify call.
you may want consider changing companies array instead of embedded object.
node.js 4.x update
you can use computed property syntax directly in object literal:
collection('users').findandmodify( {username: usern}, [['_id', 'asc']], {$set:{['companies.' + companyid]: { desksmemberships:[] }}}, {new: true}, function(){...});
Comments
Post a Comment