我有两个文档:
Category = new Schema({
storeKey: { type: String, required: true },
cod: { type: String, required: true },
name: { type: String, required: true },
visible: { type: Boolean }
},
{
timestamps: {
createdAt: "created",
updatedAt: "updated"
}
}
);
和:
Product = new Schema({
name: { type: String, required: true },
cod: String,
storeKey: { type: String, required: true },
categoryId: String,
description: { type: String, required: true },
price: { type: Number, required: true },
stockQuantity: { type: Number, required: true },
avatar: String,
visible: Boolean
}, {
timestamps: true
});
查询服务器猫鼬以找到具有聚合类别的产品
Product.aggregate([
{
$lookup: {
from: "Category",
localField: "categoryId",
foreignField: "_id",
as: "category"
}
}]
).exec((error, done) => {
if (error) res.status(500).send({
message: langs[req.query.lang],
error
});
res.status(200).send(done);
});
在本地终端上查询
db.Product.aggregate(
[{
$lookup: {
localField: "categoryId",
from: "Category",
foreignField: "_id",
as: "category"
}
}])
在终端中,$ lookup可以正常工作。对于猫鼬,它将带来重复的记录,并且不会带来现有的类别。怎么了?
答案 0 :(得分:0)
@Anthony Winzlet是正确的,应该是categories
(在pural中)必须离开category
(在pural中)而不是ObjectId
,但是,我没有定义categoryId字段在产品架构中为ObjectId
,因此它正在将字符串与const ProductSchema = new Schema({
name: { type: String, required: true },
cod: String,
storeKey: { type: String, required: true },
categoryId: { type: Schema.Types.ObjectId, ref: 'categories' },
description: { type: String, required: true },
price: { type: Number, required: true },
stockQuantity: { type: Number, required: true },
avatar: String,
visible: Boolean
}, {
timestamps: true
});
进行比较。在终端的测试中,我保存了服务器返回值,该返回值将_id字段作为字符串返回。现在可以了。谢谢!
select rules[1] as rule_1,
rules[2] as rule_2,
rules[3] as rule_3,
rules[4] as rule_4,
rules[5] as rule_5,
rules[6] as rule_6
from (
select string_to_array(rules, '|') as rules
from rulebook
) t