简体   繁体   English

MongoDB collection.aggregate 中的 $lookup 操作不匹配彼此相等的 ObjectID

[英]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: usersposts

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中的文档时,都会将名为authorObjectID字段添加到与作者的_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 ,而postsCollectionrequire('../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是一个仅包含一个objectarray ,它又包含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是一个仅包含一个objectarray ,其中包含相关文档中的所有数据。 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 .我在阅读文档时想通了。

There it says:那里说: 在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM