How do I find a mongoDB document and a second one based on its id as property of the first (like an inner join)

Issue

I’m trying to fetch all mongodb documents of the model "Conversations" using mongoose in a node.js-expres setup. I did this successfully using the .find() method. But now I want to fetch both the conversation-document as well as the respective "user"-document based on the "user" document id which is given as a property of the conversation model and i’d like to fetch them both in one object.

So a sketch: The conversation model has "_id", "sender_id" and "recipient_id". And a user has "first_name", "last_name", "email" and "password_hash".

I would like to fetch one object containing all of there properties and the _id, firstname, lastname, email and password of the user whose _id is equal to recipient_id".

But i can’t seem to find this on the internet.

Solution

If, in the Conversations Model, recipient_id is of type ObjectId and references User, then you can use the populate() function to automatically fetch the referenced Document.

Supposing your Model for the users is called User, then in the Conversations Schema, you should have :

recipient_id: { type: Schema.Types.ObjectId, ref: 'User' }

Then on your find request you can add .populate() :

Conversations.find().populate("recipient_id")

The documents returned should contain the whole associated User document in recipient_id.

For more complex requests like this, you can also check out $lookup (aggregation). Populate should be enough for your case though.

Answered By – VRZ78

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published