Mongoose嵌套填充查询

我正在尝试返回与特定用户标识关联的优惠券列表,并填充_merchant引用。

这个查询正确地填充_merchant refs。 如果我可以添加:

在哪里coupon.users.contains(myuserid)我的查询,将得到我所需要的

db.couponModel.find().populate('_merchant').exec(function(err, coupons) { res.send(coupons); }); 

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

填充(_merchant)我的查询,也将得到我所需要的。

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

架构

 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' }], }); 

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

通过$ all选项找出它。 这里的例子: https : //github.com/LearnBoost/mongoose/blob/master/test/query.test.js#L396 http://docs.mongodb.org/manual/reference/operator/all/#_S_all

最终查询码:

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

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