2016-06-07 78 views
0

我在debian 8上使用了Mongo 3.2。節點5.11.1和Mongoose。 對象被存儲查詢日期與Mongoose

{ 
    "_id": { 
    "$oid": "5756e710eb8863716246689a" 
    }, 
    "id": 735842, 
    "employee_id": 477, 
    "matricule": "1020510", 
    "name": "", 
    "date_day": "2016-04-24T22:00:00.000Z", 
    "morning_status": "P", 
    "morning_time_start": "08:16", 
    "morning_time_end": "12:12", 
    "afternoon_status": "P", 
    "afternoon_time_start": "12:57", 
    "afternoon_time_end": "18:30", 
    "working_time_theorical": 28800, 
    "working_time_employee": 34140, 
    "extra_hours": 5340, 
    "extra_hours_week": 10680, 
    "extra_hours_month": 78120, 
    "comments": "" 
} 

我想與字段來提取數據:date_day

var reporticoSchema = mongoose.Schema({ 
    id : 
    { 
     type:Number, 
     index:true, 
     required:true 
    }, 
    employee_id : 
    { 
     type:Number, 
     index:true, 
     required:true 
    }, 
    matricule : 
    { 
     type:String, 
     index:true, 
     required:true 
    }, 
    date_day : 
    { 
     type: Date, 
     index:true 
    }, 
..... 

var Reportico=module.exports = mongoose.model('Reportico',reporticoSchema) 

var dateStart=new Date('2016-04-01').toISOString(), 
dateEnd=new Date('2016-04-30').toISOString(); 

console.log('d',dateStart,dateEnd) 
var employeeId={employee_id:521,date_day:{$gte:dateStart,$lte:dateEnd}}; 
//console.log('employeeId',employeeId) 
Reportico.find(employeeId).exec(function(err, employees) { 
    console.log('result') 
    if (err)return console.log('err',err); 
    console.log('employees',employees) 
}) 

我更新的代碼以添加字段date_day 結果是空的TE格式。

+1

是如何在你的貓鼬架構中的'date_day'域定義單獨約會,你似乎已經跳過了這關鍵的部分?同樣,如果將其定義爲Date類型,那麼就不需要將JS Date對象實例解析爲字符串,只需在mongo查詢中使用原始JS Date實例,而不必將其明確地轉換爲「ISOString」格式。 – chridam

+0

是,該字段的格式是日期。你可以更明確的樣本。韓國社交協會。 –

+0

如果是這種情況,那麼你只需要去除日期實例上的'toISOString()'方法,因爲它會將它們解析爲字符串,這裏不需要'var dateStart = new Date('2016-04 -01'),dateEnd = new Date('2016-04-30'),query = {employee_id:521,date_day:{$ gte:dateStart,$ lte:dateEnd}}; Reportico.find(query).exec ...)' – chridam

回答

0

這是我與日期進行協商,我利用圖書館http://momentjs.com/

var searchParams = {}; 
var di = moment('2016-04-01', "YYYY-MM-DD").toArray(); 
var de = moment('2016-04-30', "YYYY-MM-DD").toArray(); 
searchParams['date_day'] = { $gte: new Date(di[0],di[1],di[2]), $lte: new Date(de[0],de[1],de[2]) }; 
searchParams['employee_id'] = 521 

Reportico.find(searchParams).exec(function(err, employees) { 
    console.log('result') 
    if (err)return console.log('err',err); 
    console.log('employees',employees) 
}) 
+0

嗨,結果是一樣的: {date_day: {'$ gte':Fri Apr 01 2016 00:00:00 GMT + 0200(CEST), '$ lte':Sat Apr 30 2016 00:00: 00 GMT + 0200(CEST)}, employee_id:521} - > employees [] 而這裏的格式是:星期五Apr 01 2016 00:00:00 GMT + 0200(CEST)。在Mongo中,格式爲「2016-04-24T22:00:00.000Z」 –