将文档作为字段插入

时间:2014-07-03 19:47:02

标签: mongodb mongoose

让我们说我有一个公司集合:

[{
    name: 'x',
    code: 'a',
},
{
    name: 'y',
    code: 'b',
}]

我想找到代码为'a'的公司,并将其插入另一个名为projects的集合中。我写了这样的话:

 var collectionP = db.collection('projects');
 var collectionC = db.collection('company');
 var foundCompany = collectionC.find({code: 'a'});
 db.collectionP.insert(name: 'project1', company: foundCompany);

这不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

致电find会返回cursor,而非结果集。

如果期望多个结果,您的替代方案要么在光标上迭代:

var foundCompany = collectionC.find({code: 'a'});
foundCompany.forEach(function(fc) { 
 db.collectionP.insert(name: 'project1', company: fc);
}

如果您想在一个文档中包含所有结果,请将其转换为数组:

var foundCompany = collectionC.find({code: 'a'}).toArray();
db.collectionP.insert(name: 'project1', company: foundCompany);

或者如果您只希望匹配单个公司,请使用您的语言中的findOne或其等价物:

var foundCompany = collectionC.findOne({code: 'a'});
db.collectionP.insert(name: 'project1', company: foundCompany);
相关问题