Nodejs Mongo插入子文档-动态字段名 [英] Nodejs Mongo insert into subdocument - dynamic fieldname
问题描述
{用户名:'我',公司:{您的公司":{...}}
{username:'me', companies:{"yourcompany":{...}}
我想在用户记录(用户集合)中插入公司,以便:
I want to insert a company into a user record (user collection), to make:
{用户名:'我',公司:{您的公司":{...},我的公司":{...}}
{username:'me', companies:{ "yourcompany":{...}, "mycompany":{...} }
但是名字是动态的.
var companyid = "mycompany";
.collection('users').findAndModify(
{username: usern},
[['_id', 'asc']],
{$set:{companies:{companyid: { desksmemberships:[] }}}},
{new: true}, function(){...}
为此..{username:'me',companies:{"yourcompany":{...},"companyid":{...}}
Gives this.. {username:'me', companies:{ "yourcompany":{...}, "companyid":{...} }
我该怎么做?
推荐答案
您必须以编程方式构建$set
修饰符:
You'd have to build up your $set
modifier programmatically:
var modifier = { $set: {} };
modifier.$set['companies.' + companyid] = { desksmemberships:[] };
然后将modifier
用作findAndModify
调用中的第三个参数.
And then use modifier
as the third parameter in your findAndModify
call.
您可能还需要考虑将companies
更改为数组而不是嵌入式对象.
You may also want to consider changing companies
to be an array instead of an embedded object.
Node.js 4.x更新
您现在可以使用计算属性语法可直接在对象文字中执行此操作:
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(){...});
这篇关于Nodejs Mongo插入子文档-动态字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!