I have a Module called Organisation with an array calls users in it that contains UserSchema objects. Now i need a query to get all users from all organisation documents in one array.
As you can see I am a beginner in mongodb and normaly use sql But without joins I don´t know what to do.
OrganisationModule:
const OrganisationSchema = new Schema({
name: { type: String, required: true },
users: [UserSchema],
version: String,
});
module.exports.Organisation = mongoose.model('Organisation', OrganisationSchema);
UserSchema:
module.exports.UserSchema = new Schema({
name: String,
roles: [String]
})
My first try:
routes.get('/', (req, res, next) => {
Organisation.find().populate('users').exec((err, users) => {
if (err) res.json(err.message)
else { res.json(users) }
});
The result:
[
{
"users": [
{
"roles": [ "coordinator" ],
"_id": "5aafcf80dd248f7ef86e0512",
"name": "Peter"
"__v": 0
}
],
"_id": "5aafcf80dd248f7ef86e05cf",
"name": "DEFAULT",
"__v": 1
},
{
"users": [
{
"roles": [ "admin", "coordinator" ],
"_id": "5aafcf80dd248f7ef86e0500",
"name": "Max"
"__v": 0
}
],
"_id": "5aafcf80dd248f7ef86e05ce",
"name": "Organisation_01",
"__v": 1
}
]
What I need:
[
{
"roles": [ "coordinator" ],
"_id": "5aafcf80dd248f7ef86e0512",
"name": "Peter"
"__v": 0
},
{
"roles": [ "admin", "coordinator" ],
"_id": "5aafcf80dd248f7ef86e0500",
"name": "Max"
"__v": 0
}
]