2014-10-20 171 views
4

我正在嘗試查找具有比特定日期更新或更早的位置的用戶的用戶。與Mongoose的日期比較

模式

var userSchema = new Schema({ 
    firstName: String, 
    lastName: String, 
    email: String, 
    facebookId: String, 
    googleId: String, 
    token: {type: String, unique: true, required: true}, 
    friends: [userSchema], 
    location: { 
     type: { 
      timestamp: Date, 
      accuracy: Number, 
      coordinates: { 
       lat: Number, 
       lng: Number 
      } 
     }, 
     default: null 
    } 
}, { 

查詢

userSchema.statics.findRecentUpdates = function (ids, minutesSinceLast, callback) { 
    var recentDate = new Date().removeMinutes(minutesSinceLast); 
    this.find(
     {'location.timestamp': {$lt: recentDate}}, 
     callback 
    ); 
} 

數據

db.users.find(); 
{ "__v" : 1, "_id" : ObjectId("53cecb60fe7d090000030328"), "email" : "[email protected]", "facebookId" : "9138129367", "firstName" : "Cornel", "friends" : [ ObjectId("53cecb4dfe7d090000030327") ], "lastName" : "GD", "location" : { "coordinates" : { "lat" : 18.040808, "lng" : 59.330557 }, "timestamp" : 1406061408964, "accuracy" : 1 }, "token" : "988bb52b-cc0c-492d-8c75-f1f7d882157d" } 
{ "__v" : 20, "_id" : ObjectId("53cf668eff9ef40000f76ce5"), "email" : "[email protected]", "facebookId" : "5762365752", "firstName" : "Yuan", "friends" : [ ], "lastName" : "vh", "location" : { "accuracy" : 3, "coordinates" : { "lat" : 59.356862, "lng" : 17.996661 }, "timestamp" : 1406101134199 }, "token" : "51278cb7-9e55-4cc5-b635-7cd289b2fa6a" } 
{ "__v" : 21, "_id" : ObjectId("53cecb4dfe7d090000030327"), "email" : "[email protected]", "facebookId" : "7237853051", "firstName" : "M", "friends" : [ ObjectId("53cecb60fe7d090000030328") ], "lastName" : "H", "location" : { "accuracy" : 0, "coordinates" : { "lng" : 18.0246476, "lat" : 59.3827026 }, "timestamp" : 1413838822856 }, "token" : "5d870480-05c0-4a83-ae44-cfe39692d308" } 

不管是什麼我將日期設置爲我一個總是得到一個空的結果。嘗試'location.accuracy'並設置小於或大於一個工程。

+0

不知何故,寫下一切,通讀它讓你覺得在這個問題的新途徑。也許我可以嘗試使用這一些如何不發佈第一:) – softarn 2014-10-20 21:56:40

回答

6

錯誤在於我如何存儲日期。從上面的數據可以看出,它們存儲爲毫秒1406101134199,而不是ISODate格式ISODate("2014-10-20T21:50:23.196Z")。這是由於行Date.now(),它不會返回當前的日期對象,而是返回毫秒。使用new Date()修復了錯誤。

-1

需要在分配新Date()後放置removeMinutes;

查詢:

userSchema.statics.findRecentUpdates = function (ids, minutesSinceLast, callback) { 
    var recentDate = new Date(); 
    recentDate.removeMinutes(minutesSinceLast); // It will remove the minutes 
    this.find(
     {'location.timestamp': {$lt: recentDate}}, 
     callback 
    ); 
}