查询日期与Mongoose

时间:2016-06-07 18:05:04

标签: node.js mongodb mongoose

我在debian 8上使用Mongo 3.2。节点5.11.1和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 个答案:

答案 0 :(得分:1)

这是我对日期的咨询,我使用库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)
})