【问题标题】:Filter timeperiod in node.js在 node.js 中过滤时间段
【发布时间】:2020-07-31 08:25:42
【问题描述】:

model.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);

query.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.js mongodb mongoose nodes


    【解决方案1】:

    即使 year-month-date 确实匹配,但创建文档和输入的时间不匹配,因此您可以使用聚合中的 $dateToString 来完成它,该聚合将转换 DB 中的日期字段转为 "%Y-%m-%d" 格式:

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

    测试: MongoDB-Playground

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

    【讨论】:

    • 可以使用聚合查询来完成,但我必须更改整个工作流程。包括所有其他过滤器部门名称、员工状态。有什么办法可以用 mongoose 代替 mongo
    • @ShubhamSharma :不,正如我已经提到的,您需要转换您的日期以将现有字段和输入转换为相同的格式(从代码中,您无法通过 createdOn 的秒数知道确切的时间)。 . 要么你必须改变你的写入,因为你现在不能这样做至少你必须改变你的读取以使用聚合一旦你开始改变它不需要时间使用聚合它很容易,你可以很容易地找到很多帮助
    猜你喜欢
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2020-11-27
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多