Nodejs Mongo插入子文档-动态字段名 [英] Nodejs Mongo insert into subdocument - dynamic fieldname

查看:70
本文介绍了Nodejs Mongo插入子文档-动态字段名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{用户名:'我',公司:{您的公司":{...}}

{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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆