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.
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.
Mongoose has a more powerful alternative called populate() , which lets you reference documents in other collections. Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s).
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); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With