gpt4 book ai didi

arrays - Mongoose 查询,查找 B.array 中与 A.array 中匹配的所有 B 类型项目

转载 作者:太空宇宙 更新时间:2023-11-03 22:53:40 25 4
gpt4 key购买 nike

我有一个模特

schemas.person = new mongoose.Schema({
firstname: {type: String},
lastname: {type: String},
age: Number,
email: {type: String},
gender: {type: String},
matches: [{type: mongoose.Schema.Types.ObjectId, ref: models.Person}],
});

匹配是对具有相似兴趣的另一个人的引用(即用于约会目的)

假设我有 10 个男性和 10 个女性

我想编写一个查询,为我提供一个与所有 10 个女性相互匹配的男性 - 也就是说,所有 10 个女性都出现在他的 matches 数组中,而他出现在 匹配所有 10 名女性的数组。

所以在伪代码中,它看起来像这样:

models.Person.find({"gender": "male"}).exec(function(err, men){
models.Person.find({"gender": "female"}).exec(function(err, women){
models.Person.find(some item from men.matches $in all women.matches}, function(err, result){
console.log(result);
}
}
});

最后一部分some item from men.matches $in all Women.matches我不知道如何在Mongoose中说,我找不到在线的好方法。

请注意,匹配数组如下所示:

     [
{
"$oid": "558ced061d35bd072e7b5825"
},
{
"$oid": "558ced061d35bd072e7b58a0"
},
{
"$oid": "558ced061d35bd072e7b58c6"
}
]

有什么办法可以表达这个吗?

最佳答案

两个关键标准是每个人都有匹配:

  1. 可能匹配的 id 必须位于其 matches 数组中
  2. 他们的 id 必须位于另一个人的 matches 数组中

第三个提到的标准,即匹配是女性,应该已经通过包含在 matches 数组中来考虑,假设此偏好限制反射(reflect)在那里。如果不是,为什么要限制他们的比赛在这里而不在那里?也就是说,这将是一个简单的附加查询参数,我将把它留给你。 #LoveWins

因此,这是一种方法,使用查找来获取所有男性的列表,然后使用第二个查找来检索所有可能的匹配项(不排除性别)。

models.Person.find({
gender: "male"
}).exec().then(function gotAllMen(persons) {
// persons is an array of men

// Find any matches for each person
return new Promise.all(persons.map(function(person) {
return models.Person.find({
_id: {$in: person.matches}, // Satisfies 1
matches: person._id // Satisfies 2
}).exec().then(function(match) {
// Create a new object for each match
return {
person: person,
match: match
};
});
}));
}).then(function matches(matches) {
// Have a date
});

注意:这是未经测试的代码

关于arrays - Mongoose 查询,查找 B.array 中与 A.array 中匹配的所有 B 类型项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31123093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com