Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在MongoDB中同时使用findOne和aggregate?_Node.js_Mongodb - Fatal编程技术网

Node.js 如何在MongoDB中同时使用findOne和aggregate?

Node.js 如何在MongoDB中同时使用findOne和aggregate?,node.js,mongodb,Node.js,Mongodb,假设我有一个用户列表。用户有 username, email, password, sketches 草图是另一个集合,而草图具有 title author 如果我想获取用户的草图,我必须使用aggregate查找所有草图,这些草图将作者作为其用户名 这非常有效: const data=wait userModel .合计([ {$match:{username}}, {$lookup:{from:'sketches',localField:'username',foreignField:'

假设我有一个用户列表。用户有

username,
email,
password,
sketches
草图
是另一个集合,而
草图
具有

title
author
如果我想获取用户的草图,我必须使用
aggregate
查找所有
草图
,这些草图将
作者
作为其
用户名

这非常有效:

const data=wait userModel
.合计([
{$match:{username}},
{$lookup:{from:'sketches',localField:'username',foreignField:'author',as:'sketches'},
{$limit:1}
]).toArray()
问题是一些用户没有草图;当用户没有草图时,
聚合
不会返回有关用户的任何其他信息,因此
用户名
电子邮件
,以及
密码
将变得未定义

有没有办法让
aggregate
成为可选的?比如找到用户,然后试着看看他们是否有草图


谢谢

$lookup执行外部联接,当没有要联接的文档时,它不会删除基本文档的字段

MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.insert({a:1})
WriteResult({ "nInserted" : 1 })
MongoDB Enterprise ruby-driver-rs:PRIMARY> db.foo.aggregate([{$lookup:{from:'bogus',localField:'x',foreignField:'y',as:'z'}}])
{ "_id" : ObjectId("5f2c5fbd0b0bc72d0ed504d3"), "a" : 1, "z" : [ ] }
另见