Mongoose嵌套populate查询

5
我试图返回与特定用户ID相关联的优惠券列表,并填充_merchant引用。
此查询正确地填充了_merchant引用。如果我能添加以下内容:
where coupon.users.contains(myuserid)到我的查询中,那就可以得到我需要的结果。
db.couponModel.find().populate('_merchant').exec(function(err, coupons) { 
    res.send(coupons);
});

或者这个查询可以找到我需要的正确优惠券。如果我能添加:

populate(_merchant) 到我的查询中,那么我也可以得到我需要的内容。

db.userModel.findById(req.params.id).populate('coupons').exec(function(err, user) {
    res.send(user.coupons)
});

模式(Schemas)
var userSchema = new Schema({
    email: { type: String, required: true , unique: true },
    coupons: [{ type: Schema.ObjectId, ref: 'Coupon' }]
});

var couponSchema = new Schema({
    _merchant: { type: Schema.ObjectId, ref: 'Merchant', required: true },
    couponid: { type: Number, required: true, unique: true },
    users: [{ type: Schema.ObjectId, ref: 'User' }]


});

var merchantSchema = new Schema({
    name: { type: String, required: true , unique: true }
    coupons: [{ type: ObjectId, ref: 'Coupon' }],

});

我需要这两个查询的混合来得到我想要的结果。


我猜嵌套文档的嵌套文档填充目前还不支持。请参见 https://github.com/LearnBoost/mongoose/issues/601#issuecomment-6520568 - idursun
我认为它在几天前的发布中得到了支持,但目前还没有相关文档。有什么绕过它的技巧吗?也许可以使用$in? - user1071182
https://github.com/LearnBoost/mongoose/pull/1292 - user1071182
2个回答

5

0

使用$all选项。 db.couponModel.find({users: {$all:[req.params.id]}}).populate('_merchant').exec(function(err, coupons) { console.log(coupons); })


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接