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

3
  • Possible dupe of stackoverflow.com/questions/19380738/… Commented Nov 30, 2015 at 3: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 Commented Dec 1, 2015 at 5: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 :( Commented Dec 1, 2015 at 5:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

thanks, this works as desired after adding the missing brackets around the last arg
@Scott This will not exclude users that don't have at least one booking before today.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.