首页 > 解决方案 > 在 node.js 中过滤时间段

问题描述

模型.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const user = new Schema ({
id:{type:mongoose.Types.ObjectId},
firstName:{type:String, required:true},
lastName:{type:String, required:true},
pic:{type:String},
gender:{type:String},
dob:{type:String},
maritalStatus:{type:String},
nationality:{type:String, enum: ['Indian', 'Others']},
streetAddress: {type:String},
city: {type:String},
state: {type:String},
postalCode: {type:String},
country: {type:String},
phone: {type: String},
email: {type:String},
jobTitle: {type:String},
department: {type:mongoose.Schema.Types.ObjectId, ref:'department'},
dateOfJoining: {type:String},
employeeStatus: {type:String, enum: ['Working', 'Resigined', 'Terminated']},
kra: {type:String},
assignedSupervisor: {type:String},
assignedSubordinate: {type:String},
workExperience : {type:String},
skills: {type:String},
password: {type:String, required:true},
createdOn : {type:Date, default:Date.now}  <<<<=====   filter will work on this
})

 module.exports = mongoose.model("user", user);

查询.js

exports.getUser = async(userId, employeeStatus, department, firstName, timePeriod) => {
if (timePeriod) {
    if (timePeriod = 'today') {
       ====>>>>>>> I want here if req.query.timeperiod = today then it show result whose createdOn is today. createdOn is the field in user schema given above 
    }

}
let queryFilters = { employeeStatus, department, firstName, timePeriod}
queryFilters = JSON.parse(JSON.stringify(queryFilters));
console.log(queryFilters)
return await model.find(queryFilters).populate("department").exec();
}

handler.js

getUser = async (req, res, next) => {
try {
    let user = await userController.getUser(req.query.employeeStatus, req.query.department, req.query.firstName, req.query.timePeriod)
    req.data = user
    next()
}
catch (e) {
    req.status = 400;
    next(e)
}
}

查询工作正常。我想要如果 req.query.timePeriod = today 那么 query.js 必须返回其 createdOn 具有今天日期的结果。createdOn 是在 model.js 中看到的字段。我卡在这里了。谁能帮帮我吗?

标签: node.jsmongodbmongoosenodes

解决方案


即使年-月-日期匹配,但文档创建和输入的时间不匹配,因此您可以使用聚合中的$dateToString来完成,它将数据库中的日期字段转换为“%Y-%m-%d”格式 :

{
    $match: {
      $expr: {
        $eq: [
          {
            $dateToString: {
              format: "%Y-%m-%d",
              date: "$createdOn"
            }
          },
          "2020-04-17" /** Input */
        ]
      }
    }
  }

测试: MongoDB-游乐场

注意: MongoDB 中的所有日期都以 UTC 格式存储。因此,当您今天说时,为输入“2020-04-17”取出的字符串应指 UTC。假设当您在 2020 年 4 月 17 日CST(美国中部时间)晚上 11 点左右添加文档时,文档createdOn将在 4 月 18 日,因为UTCCST之前,同样,当您在 4 月 18 日凌晨 1 点从ISTcreatedOn执行此操作时,文档将在 4 月 17 日因为UTC落后于IST。因此,在您的 node.js 代码中,您可以执行诸如new Date().toISOString().split('T')[0]获取UTC转换日期之类的操作。如果您不想要这些转换,也许您可​​以像这样存储字符串文件中的“2020-04-17”。如果您想知道如何使用.populatewith.aggregate()然后检查这个 :: how-to-use-populate-and-aggregate-in-same-statement


推荐阅读