Nodejs Mongo insert into subdocument - dynamic fieldname

前端 未结 2 1042
时光取名叫无心
时光取名叫无心 2020-12-03 20:25

{username:\'me\', companies:{\"yourcompany\":{...}}

I want to insert a company into a user record (user collection), to make:

{username:\'me\', companies:{ \

2条回答
  •  孤城傲影
    2020-12-03 20:56

    You'd have to build up your $set modifier programmatically:

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

    And then use modifier as the third parameter in your findAndModify call.

    You may also want to consider changing companies to be an array instead of an embedded object.

    Node.js 4.x Update

    You can now use the computed property syntax to do this directly in the object literal:

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

提交回复
热议问题