Search code examples
node.jsmongodbmongoosenosqlisodate

How to compare user input date with mongodb ISODate object


I am new to MongoDB and I stuck at one point, following is the explanation.

I am getting a date in format dd-mm-yyyy and I want to find all the data according to the particular date which I am getting. But on the mongo side, I am having a field createdAt, which contains ISODate formatted values. While comparing these two I am not getting any data.

mySchema.find({createdAt: {"$eq": date}}).exec();

Here createdAt value in the database is ISODate("2020-05-05T14:49:37.210Z") and we are getting a date as 05-05-2020

Please help me out to understand where I am doing wrong.


Solution

  • You can convert the ISO date to any string format you wan in aggregation pipeline by dateToString function and then compare it.

    Below is the example of how to create a schema and then use it code.

    // UserModal.js
    
    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    
    
    var UserSchema = new Schema({
        first_name: {
            type: String,
            required: true
        },
    
        last_name: {
            type: String,
            required: true
        },
        ......
    }, { timestamps: true });
    
    
    //make this available to our users in Node applications
    module.exports.User = mongoose.model('User', UserSchema);
    

    Then in controller

    const User = require("UserModal").User;
    
    User.aggregate([
      {
        $addFields: {
          "dateString": { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } }
        }
      },
      {
        $match: {
          dateString: {
            $eq: "2020-05-05"
          }
        }
      }
    ]).exec((err, records) => {
      if (err) throw err;
      console.log(records);
    })