我的简化架构如下所示:
var personSchema = new Schema({
firstName: String,
lastName: String
});
var teamSchema = new Schema({
people: [personSchema]
});
module.exports = mongoose.model('Team', teamSchema);
我想找到所有名为" Alan"的人。我看了this very similar question,但它找到了团队,而不是人。我认为Same here。即使我没有收集人员,是否有退回人员的查询?
我认为我可以使用引用的技术找到团队,然后拔出他们的人。我想是这样的事情:
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
});
但是,这是一种更直接的方式,对吗?
答案 0 :(得分:1)
根据您的意见,也许您可以试试这个
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);
})