Reputation: 15
I'm trying to query an array of references after populating with their corresponding objects. I have a feeling I'm either not using the correct operational $... or my approach isnt the right way to go about what I need to do.
Ill give an example to clarify exactly what I'm trying to do. Say I have a collection of Users, who can have multiple Booking documents associated with them. I need find all Users who live in a certain location AND have at least one Booking whose start date is before today.
The models are along the lines of:
var Booking = new mongoose.Schema({
starts_at: { type: Date },
ends_at: { type: Date },
//...
});
var User = new mongoose.Schema({
name: String,
location: String,
bookings: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Booking' }],
//...
});
And the code/query I'm trying is along the lines of:
User.find({ 'location': 'some place' })
.populate('bookings')
.where({ 'bookings.starts_at': { $lte: new Date() } })
.exec(function(err, users) {
//...
});
Any help or insights would be great
Upvotes: 1
Views: 160
Reputation: 514
User
.find({ 'location': 'some place'})
.populate('bookings', null, 'starts_at' : { $lte: new Date()})
.exec(function(err, result) {
if (!err) {
console.log(result);
} else {
console.log(err)
}
});
Please try with this!!
Upvotes: 1