[英]MongoDB $lookup operation inside collection.aggregate not matching ObjectIDs that are equal to each other
I have, in the same database, the following two collections: users
and posts
.在同一个数据库中,我有以下两个 collections:
users
和posts
。
Whenever a document inside posts
is created server-side, an ObjectID
field named author
is added to the document that matches the author's _id
.每当在服务器端创建
posts
中的文档时,都会将名为author
的ObjectID
字段添加到与作者的_id
匹配的文档中。
For example:例如:
As can be seen, the ObjectID
properties are the same.可以看出,
ObjectID
属性是相同的。
However, when I call the following aggregate
method on the posts
collection, the $lookup
operation apparently fails, not adding an object.但是,当我在
posts
集合上调用以下aggregate
方法时, $lookup
操作显然失败了,没有添加 object。
Where id
is an argument passed down to the function that contains the string
for the post
document, and postsCollection
is require('../db.js').db().collection('posts');
其中
id
是传递给 function 的参数,其中包含post
文档的string
,而postsCollection
是require('../db.js').db().collection('posts');
What I expected我所期望的
posts
is an array
containing just one object
, that in turn contains the data for the post
document with the _id
property matching the incoming id
argument. posts
是一个仅包含一个object
的array
,它又包含post
文档的数据,其_id
属性与传入的id
参数匹配。
This object
should have all the properties from the document and one additional property named 'authorDocument'
that contains all the data from the user
document.这个
object
应该具有文档中的所有属性和一个名为'authorDocument'
附加属性,该属性包含user
文档中的所有数据。
What happens发生什么了
posts
is an array
containing just one object
with all the data from the relevant document. posts
是一个仅包含一个object
的array
,其中包含相关文档中的所有数据。 However , the authorDocument
property is not added.但是,未添加
authorDocument
属性。
This is what I get by calling console.log(posts[0])
:这是我通过调用
console.log(posts[0])
得到的:
What I have tried我试过的
I've created another post and also relogged (to create another session).我创建了另一个帖子并重新登录(以创建另一个会话)。 Same problem.
同样的问题。
I've also tried finding the document with another method: collection.findOne
and it worked with the author
property from posts[0]
object.我还尝试使用另一种方法查找文档:
collection.findOne
并且它与posts[0]
object 中的author
属性一起使用。
gets me得到我
I have also tried comparing the author
field with the _id
field from the user, by doing this:我还尝试将
author
字段与用户的_id
字段进行比较,方法是:
It returns true
.它返回
true
。
Turns out it was a very simple typo.结果证明这是一个非常简单的错字。 I figured it while reading the documentation .
我在阅读文档时想通了。
I hadn't listed the operations inside an array
of operations, and that's why the second operation ( $lookup
) was not being recognized.我没有列出操作
array
中的操作,这就是第二个操作 ( $lookup
) 未被识别的原因。
By adding the following brackets, the code now runs perfectly:通过添加以下括号,代码现在可以完美运行:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.