Nodejs Mongo insert into subdocument - dynamic fieldname

流过昼夜 提交于 2019-11-26 18:31:50

问题


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

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

{username:'me', companies:{ "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 this.. {username:'me', companies:{ "yourcompany":{...}, "companyid":{...} }

How do I do this?


回答1:


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(){...});



回答2:


I've seen this question on quite a few posts, some of them quite complex- call me crazy but you can do this (node + mongo):

My db schema 'matches' is set to an array. In the mongo data [match.matchId] becomes '2028856183'.

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

You can use any variable in the brackets.



来源:https://stackoverflow.com/questions/12184626/nodejs-mongo-insert-into-subdocument-dynamic-fieldname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!