[英]How to find mongoose subdocuments matching some criterion
My simplified schema looks like this: 我的简化架构如下所示:
var personSchema = new Schema({
firstName: String,
lastName: String
});
var teamSchema = new Schema({
people: [personSchema]
});
module.exports = mongoose.model('Team', teamSchema);
And I want to find all the persons named "Alan". 我想找到所有名为“艾伦”的人。 I looked at this very similar question , but it finds teams, not people. 我看着这个非常相似的问题 ,但它发现的是团队,而不是人员。 Same here , I think. 我想这里也是 。 Is there a query that returns persons even if I don't have a persons collection? 即使我没有人员集合,有没有返回人员的查询?
I think I can use the cited techniques to find teams, then pull out their people. 我想我可以使用引用的技术来找到团队,然后拔出他们的人。 Something like this, I guess: 我猜是这样的:
teams
.find({})
.populate({
path: 'people',
match: { firstName: { $eq: "Alan" }}
})
.exec().then(function(teams) {
var people = [];
// walk through the found teams, looking through all the people
// whenever one is found named Alan, add it to the people array
});
But there's a more direct way, right? 但是还有一种更直接的方法,对吗?
Per your comments, maybe you can try this one 根据您的评论,也许您可以尝试这个
teamSchema.statics.findPeople = function(name, cb) {
return this.find({'people.firstName': name}, {'people.$': 1}, cb);
}
var Team = mongoose.model('Team', teamSchema);
Team.findPeople('Alan', function(err, data) {
if (err)
console.log(err);
else
console.log(data);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.