1

I'm using mogoosejs and have a data model:

var UserSchema = new Schema({
    username: {type: String, required: true},
    location: {type: [Number], required: true}, // [Long, Lat]
    created_at: {type: Date, default: Date.now},
    updated_at: {type: Date, default: Date.now}
});

Now on that schema I want to perform a query that will find all the users within certain area, so I did as follows:

var query = User.find({});
if(distance){
    query = query.where('location').near({ center: {type: 'Point', coordinates: [long, lat]},
    maxDistance: distance * 1609.34, spherical: true});
}

So that works super well, but now I want to add another parameter to this query - date. So I want to find all users within a specific location and that created their accound during last 16 hours... How should I modify my query to get all those results? Thanks a lot for any clues!

1 Answer 1

1

To add the date query, create a date object that represents the datetime 16 hours ago:

var start = new Date();
start.setHours(start.getHours()-16);

Use the above in your query now as:

// get coordinates [ <longitude> , <latitude> ]
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;
var criteria = { 
        "created_at": { "$gte": start }
        "location": {
            "$near": coords,
            "$maxDistance": distance * 1609.34
        }
    },
    query = User.find(criteria);

If the opportunity shows, use moment.js library, a super handy utility for doing manipulations like this. To use it for such scenario, you'd call the subtract() method as:

var start = moment().subtract(16, 'hours'),
    criteria = { "created_at": { "$gte": start }},
    query = User.find(criteria);
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much! one more thing - how can I add more criteria (like my location mentioned in my question) to criteria ?
@randomuser1 You could add it in the query object as I've shown in my updated answer.

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.