Nodejs Mongo inserts a dynamic field name into a subdocument

{username: 'me', company: {"yourcompany": {...}

I want to insert a company in a user record (user collection) to do:

{username: 'me', company: {"yourcompany": {...}, "mycompany": {...}}

But the name is dynamic.

var companyid = "mycompany";

.collection('users').findAndModify(
{username: usern}, 
[['_id', 'asc']], 
{$set:{companies:{companyid: { desksmemberships:[] }}}},    
{new: true}, function(){...}

Gives it .. {username: 'me', company: {"yourcompany": {...}, "companyid": {...}}

How to do it?

+3
source share
2 answers

You must create your modifier $setprogrammatically:

var modifier = { $set: {} };
modifier.$set['companies.' + companyid] = { desksmemberships:[] };

And then use modifieras the third parameter in the call findAndModify.

companies .

Node.js 4.x

, :

collection('users').findAndModify(
    {username: usern}, 
    [['_id', 'asc']], 
    {$set:{['companies.' + companyid]: { desksmemberships:[] }}},    
    {new: true},
    function(){...});
+6

, - , (node + mongo):

My db schema 'matches' . mongo [match.matchId] "2028856183".

db.update({key: value}, {matches: [{[match.matchId] : match}] }, callback);
db.update(what to find, what to change it to, what to do next)

.

0

All Articles