我的数据库收藏集:
名称列表:
{
"_id": {
"$oid": "5bd587adfb6fc074abb12cb2"
},
"name": "name 1",
"year": "3",
"id": "101"
}
,
{
"_id": {
"$oid": "5bd587cffb6fc074abb12cb8"
},
"name": "name 2",
"year": "4",
"id": "102"
},
{
"_id": {
"$oid": "5bd587e9fb6fc074abb12cbe"
},
"name": "name 3",
"year": "2",
"id": "103"
}
获奖者:
{
"_id": {
"$oid": "5bd58921fb6fc074abb12ce8"
},
"id": "301",
"winner": [
"101",
"102"
]
}
我需要遍历获奖者集合中的数组(id字段),并在名称列表集合中找到与获奖者集合中的数组(id)匹配的数据(名称列表集合中的id字段)的模块。
//I have two Schema namelist and winner
var Schema = mongoose.Schema;
var namelist = new Schema({
_id: mongoose.Schema.ObjectId,
id: String,
name: String,
year: String
},
{
strict: false
});
var Namelist = mongoose.model('namelist', namelist);
var winner = new Schema({
_id: mongoose.Schema.ObjectId,
id: String,
winner:[ String ]
},
{
strict: false
});
var Winner = mongoose.model('winner', winner);
//populate part
Namlist.find({ id: id }).
populate('winner').
exec(function (err, data) {
if (err) return handleError(err);
console.log(data);
});
我需要一个模块,该模块遍历获奖者集合中的数组(id字段),并在名称列表集合中找到与获奖者集合中的数组(id)相匹配的数据(名称列表集合中的id字段)。
预期产量
{
"_id": {
"$oid": "5bd587adfb6fc074abb12cb2"
},
"name": "name 1",
"year": "3",
"id": "101"
}
,
{
"_id": {
"$oid": "5bd587cffb6fc074abb12cb8"
},
"name": "name 2",
"year": "4",
"id": "102"
}
除了id:103之外,它还应该使用获胜者收藏集显示其他数据
预先感谢
答案 0 :(得分:1)
要在猫鼬中使用.populate()
,您需要使用ref
作为文档说明(here)来定义实体之间的引用。在这种情况下,您可以使用常规的$lookup合并两个集合中的数据,然后可以$unwind和$replaceRoot从namelists
中获取项目。试试:
let result = await Winner.aggregate([
{ $match: { id: "301" } },
{ $lookup: { from: "namelists", localField: "winner", foreignField: "id", as: "winner" } },
{ $unwind: "$winner" },
{ $replaceRoot: { newRoot: "$winner" } }
]);
console.log(result);
或使用旧的回调样式:
Winner.aggregate([
{ $match: { id: "301" } },
{ $lookup: { from: "namelists", localField: "winner", foreignField: "id", as: "winner" } },
{ $unwind: "$winner" },
{ $replaceRoot: { newRoot: "$winner" } }
], function(err, result){
console.log(result);
});
打印:
[ { _id: 5bd587adfb6fc074abb12cb2,
name: 'name 1',
year: '3',
id: '101' },
{ _id: 5bd587cffb6fc074abb12cb8,
name: 'name 2',
year: '4',
id: '102' } ]