Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose nested populate query

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.

like image 507
user1071182 Avatar asked Feb 13 '13 12:02

user1071182


People also ask

How do I populate a nested document in MongoDB?

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.

How does populate work in Mongoose?

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.

What is path in Mongoose populate?

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).


1 Answers

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); })
like image 197
user1071182 Avatar answered Sep 28 '22 05:09

user1071182