1

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

Scott
  • 15
  • 3
  • Possible dupe of http://stackoverflow.com/questions/19380738/mongoose-nested-query-on-model-by-field-of-its-referenced-model – JohnnyHK Nov 30 '15 at 03:37
  • very similar, but the method there would give me with an array of matching Bookings, where as I need the Users as the result to work with – Scott Dec 01 '15 at 05:35
  • also, Bookings contains no back-reference - the reference is part of the same model that the inital/first query is performed on (User) so that method unfortunately doesnt work :( – Scott Dec 01 '15 at 05:47

1 Answers1

1
 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!!

Soni Pandey
  • 514
  • 5
  • 16
  • thanks, this works as desired after adding the missing brackets around the last arg – Scott Dec 01 '15 at 05:31
  • @Scott This will not exclude users that don't have at least one booking before today. – JohnnyHK Dec 01 '15 at 14:27
  • thanks @JohnnyHK , yea I filter those out with a `users = users.filter(function(user){ return user.bookings.length; })` - unless you can suggest a method I can include in the DB query? – Scott Dec 04 '15 at 05:13