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.
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'
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With