I am trying to get results from mongodb using(mongoose) the below query.
RolesModel.findOne({ role: 'reviewer' }, function (err, role) {
if (err) return res.status(500).send("Error getting data of reviewers");
console.log(role._id);
UserModel.find({ roles: role._id }, function (err, reviewers) {
if (err) return res.status(500).send("Error getting reviewers from user table");
res.send(reviewers);
});
});
its not returning any values. User schema is as follows:
var UserSchema = new Schema({
id: String,
//some other fields
roles: Array
}, { collection: 'conf_user' });
currently I have data like this.
{ "_id" : ObjectId("57c2fa7156c1f6291d373227"), "roles" : [ "57c2fa6583b7bf0c1d452877" ], "__v" : 0 }
"57c2fa6583b7bf0c1d452877"
this id is from "roles" table.
If i put, UserModel.find({ roles: '57c2fa6583b7bf0c1d452877'}
then it will return me values.
Not sure what I am missing here. I have tried this also
{ roles: { $elemMatch: { roles: role._id } }
答案 0 :(得分:1)
role._id
will return an id of type ObjectId
, but roles are stored in the form of array of StringIds. Convert the ObjectId to string value using role._id.toString()
before you pass the role._id
to UserModel.find
RolesModel.findOne({ role: 'reviewer' }, function (err, role) {
if (err)
return res.status(500).send("Error getting data of reviewers");
UserModel.find({ roles: role._id.toString() }, function (err, reviewers) {
if (err)
return res.status(500).send("Error getting reviewers from user table");
res.send(reviewers);
});
});