简体   繁体   中英

Filter timeperiod in node.js

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)
}
}

Query is working fine. I want if req.query.timePeriod = today then query.js must return result whose createdOn is having today's date. createdOn is field as seen in model.js. I have stucked here. Can anyone please help me?

Even though the year-month-date does match but time when document got created & input doesn't match, So you can do it using $dateToString from aggregation which converts date field in DB to "%Y-%m-%d" format:

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

Test: MongoDB-Playground

Note: All dates in MongoDB are stored in UTC. So, when you say today then the string taken out for input "2020-04-17" should refer to UTC. Let's say when you add a document around 11pm CST (Central Time in USA) on April 17th 2020 then document's createdOn will be April 18th as UTC is ahead of CST , Similarly when you do it from IST at 1am April 18th then documents createdOn will be April 17th cause UTC is behind IST . So in your node.js code you can do something like new Date().toISOString().split('T')[0] to get UTC converted date. If you don't want these conversions maybe you can store just string like this "2020-04-17" in documents. If you wonder how to use .populate with .aggregate() then check this:: how-to-use-populate-and-aggregate-in-same-statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM