我有一个名为"组织"的模块,其中包含用户,其中包含用户chema对象。现在,我需要查询以使所有组织文档中的所有用户都以一个数组的形式获取所有用户。
您可以看到我是MongoDB的初学者,并且常规使用SQL但是没有加入,我不知道该怎么办。
OrganisationModule:
const OrganisationSchema = new Schema({
name: { type: String, required: true },
users: [UserSchema],
version: String,
});
module.exports.Organisation = mongoose.model('Organisation', OrganisationSchema);
用户chema:
module.exports.UserSchema = new Schema({
name: String,
roles: [String]
})
我的第一次尝试:
routes.get('/', (req, res, next) => {
Organisation.find().populate('users').exec((err, users) => {
if (err) res.json(err.message)
else { res.json(users) }
});
结果:
[
{
"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
}
]
我需要:
[
{
"roles": [ "coordinator" ],
"_id": "5aafcf80dd248f7ef86e0512",
"name": "Peter"
"__v": 0
},
{
"roles": [ "admin", "coordinator" ],
"_id": "5aafcf80dd248f7ef86e0500",
"name": "Max"
"__v": 0
}
]
这个
Organization.find(
{},
{_id: 0, users: 1}
)
将返回
[
{
users: {
roles: ['coordinator'],
_id: '5aafcf80dd248f7ef86e0512',
name: 'Peter',
....
},
},
{
users: {
roles: ['admin', 'coordinator'],
_id: '5aafcf80dd248f7ef86e0500',
name: 'Max',
....
},
},
];
这不是您想要的,但我发现最符合您的需求。
您可以在此处找到更多信息:
- https://stackoverflow.com/a/42558955/11120444
- https://stackoverflow.com/a/9601614/11120444
其他,还有其他方法
// Meaby you will need to add await
const users = Organization.find({}).map((item: any) => item.users);
在mongodb中您可以使用 $lookup
执行该操作。
请在此处学习$查找:https://docs.mongodb.com/manual/reference/poerator/aggregation/aggregation/lookup/
在猫咪中您可以使用populate()
例如:
Organization.find().populate('users')
在这里学习猫绿色的填充:http://mongoosejs.com/docs/populate.html