I'm trying to return a list of coupons that are associated with a specific userid and populate the _merchant references.
This query correctly populates the _merchant refs. If I could add:
where coupon.users.contains(myuserid) to my query that would get what I need
db.couponModel.find().populate('_merchant').exec(function(err, coupons) {
res.send(coupons);
});
Or this query finds the correct coupons that I need. If I could add:
populate(_merchant) to my query that would also get what I need.
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' }],
});
I need some hybrid of these two queries to get what I want.
Figured it out using the $all option. Examples here: https://github.com/LearnBoost/mongoose/blob/master/test/query.test.js#L396 http://docs.mongodb.org/manual/reference/operator/all/#_S_all
Final query code:
db.couponModel.find({users: {$all:[req.params.id]}}).populate('_merchant').exec(function(err, coupons) { console.log(coupons); })
Use $all option. db.couponModel.find({users: {$all:[req.params.id]}}).populate('_merchant').exec(function(err, coupons) { console.log(coupons); })