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()
You are getting an array because find() returns all matches.
Get the property from the first object. Use it with the 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].createdAt);
console.log(finalDate);
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)
let fromDate = new Date(date);
console.log(fromDate.getDate())
Also look here : https://docs.mongodb.com/manual/reference/method/Date/#return-date-as-date-object