Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 608
Varun Gopal K.P Avatar asked Dec 01 '18 12:12

Varun Gopal K.P


1 Answers

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'
}
like image 153
younesbenallal Avatar answered Sep 18 '22 10:09

younesbenallal