如何找到符合某些条件的猫鼬子文档

How to find mongoose subdocuments matching some criterion

本文关键字:文档 条件 何找      更新时间:2023-09-26

我的简化模式如下所示:

var personSchema = new Schema({
    firstName: String,
    lastName: String
});
var teamSchema = new Schema({
    people: [personSchema]
});
module.exports = mongoose.model('Team', teamSchema);

我想找到所有叫"艾伦"的人。 我看了这个非常相似的问题,但它找到了团队,而不是人。 我想这里也一样。 是否有查询可以返回人员,即使我没有人员集合?

我想我可以使用引用的技术来寻找团队,然后拉出他们的人。 像这样的东西,我猜:

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
});

但还有更直接的方法,对吧?

根据您的评论,也许您可以尝试一下

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);
})