I am trying to find all documents that match with custom field in node.js.
node.js code:
req.app.db.models.Property.find({
user: {
id: req.params.id
}
}).exec(function(err, user) {
if (err) {
return next(err);
}
console.log("id:" + req.params.id);
console.log("user:" + user);
res.status(200).json(user);
});
But, console shows like this
id:5941cfc42df14b2fe811d531
user:
And the schema is like below
user: {
id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
name: { type: String, default: '' },
email: { type: String, defaul: ''}
},
propertyType: { type: String, default: '' },
..........
}
It seems that it can't find documents. What's wrong with this? Several documents exist on Property Collection.
The problem is in your query, its finding a user having an object id only. So what you are actually equating is "user" with "{ id: req.params.id }" which return only id parameter. So for your solution do following:
var query = {'user.id':req.params.id}
Property.find(query).exec(function(err, user) {
if (err) {
return next(err);
}
if you want to specify the type of object returned, if found. You can mention it as follows:
Property.find(query,'user.id user.name').exec(...)
this will return an object with user id and email only and not the name.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.