我有一个组织的集合。每个组织都有成员。我想运行查询以检查用户是否是该组织的成员。
我试过了:
mongoose.model('organization').find({orgId: paramOrgId}, function(err, organization){
organization.find({'members.user':req.user._id}, function(err, user){
if(!user) res.send(401) //The user is not a member in organization
if(user) res.send(200);
});
}
return res.send(401);
});
显然你没有找到'在回调上。我应该怎么做呢?
组织文档示例:
> db.organizations.find().forEach(printjson);
{
"_id" : ObjectId("5381d5d11409f125475fcc90"),
"orgId" : 5,
"title" : "ExampleCorp",
"members" : [
{
"tier" : 1,
"user" : ObjectId("5381d5d11409f125475fcc8c")
},
{
"tier" : 2,
"user" : ObjectId("5381d5d11409f125475fcc8d")
},
{
"tier" : 3,
"user" : ObjectId("5381d5d11409f125475fcc8e")
}
]
}
答案 0 :(得分:0)
如果您只想检查用户是否是组织的成员,则在一个查询中。
// Use findOne so that it returns one document instead of a collection
mongoose.model('organization').findOne({
// Instead of querying twice, just set both conditions
'orgId': paramOrgId,
'members.user':req.user._id
},
'_id', // We'll just select the _id field. We don't need the whole organization document
function (err, org) {
if (err)
return res.send(500); // Error!
if (org)
return res.send(200);
else
return res.send(401);
});