Reverse populate in mongoose

How can i reverse populate in mongo. I have 2 schema’s

User:

var user_scheme = new mongoose.Schema({
  name:String,
  age:Number,
  roles:{
    type:mongoose.Schema.Types.ObjectId,
    ref:'Role'
  }
 });

Role:

var role_scheme = new mongoose.Schema({
  name:String,
});

Documents:

///user
{
"_id" : ObjectId("5bf9a19b01ce3e19b440aed8"),
"name" : "user1",
"age" : 22,
"roles" : ObjectId("5c0242621ab7b677e6b2e01e"),
"__v" : 0
}
 ///role
{
"_id" : ObjectId("5c0242621ab7b677e6b2e01e"),
"name" : "Admin"
}

Code:

User.find().populate('roles').exec(function (err, data) {
 res.json(data);
})

Here i can get roles under user, But how i get users under each role.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The $lookup function by @Ashh was not working for me.

I used a more recent version :

$lookup: {
    from: 'users',
    localField: '_id',
    foreignField: 'organization',
    as: 'users'
}

Solution 2

You can use below $lookup aggregation

Role.aggregate([
  { "$match": { "name" : "Admin" }},
  { "$lookup": {
    "from": "users",
    "let": { "roleId": "$_id" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$roles", "$$roleId"] } } }
    ],
    "as": "users"
  }}
])

Solution 3

you can use mongoose-reverse-populate module.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply