How to save date type dd/mm/yyyy format in mongodb

Viewed 5553

Tried to save date format like dd/mm/yyyy in mongodb but this is saved like 2020-06-01T18:30:00.000Z.I want to save like 2020-06-01 in mongodb.How to do it? Here my code:

data.model.js:

const mongoose = require('mongoose');

var userSchemaData = new mongoose.Schema({
    p_id: {
        type: String
    },
    product_today: {
        type: Date
    },
    product_afterfive: {
        type: Date
    } 
}, {
    versionKey: false,
    collection: 'data'
});

module.exports = mongoose.model('Data', userSchemaData);

data.controller.js:

var moment = require('moment');
var todayDate = new Date(); 
var afterfiveDays = new Date(new Date().getTime() + (5 * 24 * 60 * 60 * 1000));

module.exports.insertData = (req, res, next) => {
    let collectionName = req.query.collection;
    var Product= mongoose.model(collectionName); 
    var todayDateFormat = moment(todayDate, 'DD-MM-YYYY').format('MM-DD-YYYY');
    var afterfiveDaysFormat = moment(afterfiveDays, 'DD-MM-YYYY').format('MM-DD-YYYY');

    var product = new Product({
            p_id: "CS1",
            product_today:todayDateFormat,
            product_afterfive: afterfiveDaysFormat 
    });

        product.save(function(error, document) { 
            if (error) { console.log(error); } else {
                console.log("Successful inserted");

                res.json({ success: true, msg: 'User inserted.', cname: collectionName });
            }
});
1 Answers

As stated in the documentation, mongoose will create a native Date object from the provided date value (see https://mongoosejs.com/docs/tutorials/dates.html)

The reason for this is probably that MongoDB's underlying type for "date" is

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.

so there's no date-type without the time. You can make sure in your application-code to insert dates with the time set to 00:00:00 or store the the "YYYY-MM-DD"-value as a String instead of a Date.

Related