Reputation: 323
I have, in the same database, the following two collections: users
and 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
.
For example:
As can be seen, the ObjectID
properties are the same.
However, when I call the following aggregate
method on the posts
collection, the $lookup
operation apparently fails, not adding an 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');
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.
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.
What happens
posts
is an array
containing just one object
with all the data from the relevant document. However, the authorDocument
property is not added.
This is what I get by calling 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.
gets me
I have also tried comparing the author
field with the _id
field from the user, by doing this:
It returns true
.
Upvotes: 0
Views: 39
Reputation: 323
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.
By adding the following brackets, the code now runs perfectly:
Upvotes: 1