Home > Enterprise >  What is the correct way of saving values into a constant in mongoose?
What is the correct way of saving values into a constant in mongoose?

Time:10-05

I have a user model and I have used timestamps in it. I need to access the createdAt date and save it in a variable. I tried

const date = await User.find({
      serial: serialId,
    }).select('-_id createdAt');

But this is returning

[ { createdAt: 2021-09-23T10:47:24.400Z } ]

However the only thing that i want to be saved inside my date constant is

2021-09-23T10:47:24.400Z

that also as a Date()

CodePudding user response:

You are getting an array because find() returns all matches. Get the first object and use Date() constructor to get your required value as date.

Try this:

const date = await User.find({
      serial: serialId,
    }).select('-_id createdAt');

let finalDate = new Date(date[0]);
console.log(finalDate);

CodePudding user response:

Use findOne, it returns one document. documentation of findOne : https://mongoosejs.com/docs/api.html#model_Model.findOne

const date = await User.findOne({
          serial: serialId,
        }, '-_id createdAt').exec();
    
    console.log(date.createdAt)

or

const {createdAt :  date}= await User.findOne({
          serial: serialId,
        }, '-_id createdAt').exec();
    
    console.log(date)

const {createdAt :  date} = { createdAt: '2021-09-23T10:47:24.400Z' }
console.log(date)

  • Related