Set
Set

Reputation: 323

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.

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:

enter image description here enter image description here

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.

enter image description here

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]):

enter image description here


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.

enter image description here

gets me

enter image description here

I have also tried comparing the author field with the _id field from the user, by doing this:

enter image description here

It returns true.

Upvotes: 0

Views: 39

Answers (1)

Set
Set

Reputation: 323

Turns out it was a very simple typo. I figured it while reading the documentation.

There it says: enter image description here

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:

enter image description here

Upvotes: 1

Related Questions