alyx
alyx

Reputation: 2733

Mongo Node query within 1 hour of timestamp

My query to find all objects within 1 hour ago of current time (based on timestamps) is not returning data:

The schema:

var visitSchema = mongoose.Schema({
  timestamp: { type: Date, default: Date.now },
  userID: String,
  userName: String,
  worldID: String
});

Node + Mongoose back-end:

var d = new Date() - 60 * 60 * 1000; //1 hour ago (from now)
   
var qw = {
    timestamp: { 
        $gt: d
    },
    worldID: req.query.worldID
}    
db.collection('visits').find(qw).sort({_id: -1}).toArray(fn(req, res));

Upvotes: 0

Views: 2179

Answers (1)

jmar777
jmar777

Reputation: 39669

var d = new Date() - 60 * 60 * 1000; is returning a number (unix timestamp), not an actual Date.

Given your schema, it looks like you're storing actual Dates int the database, so you'll need to do your timestamp math, and then convert back into a Date:

var d = new Date(Date.now() - 60 * 60 * 1000);

Upvotes: 1

Related Questions