I am a bit new to MongoDB and Mongoose and I want to convert the created timestamp from Mongo into a Unix timestamp for easier comparison.
async getComments(params) {
//user who the comments was made for
let _id = params;
try {
//get comments for current user
let uFilter = { user: _id };
let uFields = { comment: 1, createdBy: 1, created: 1 };
const resultsData = await Comments.find(uFilter, uFields).populate({
path: 'createdBy',
select: ['firstName', 'lastName'],
});
console.log(resultsData);
return { d: resultsData };
} catch (error) {
console.log(error);
return false;
}
}
What I get back is:
{
_id: new ObjectId("0000000000000000000"),
comment: 'Comment made by user',
created: 2022-01-13T09:21:25.689Z,
createdBy: {
_id: new ObjectId("61b750324596e539c7cadb9b"),
firstName: 'John',
lastName: 'Doe'
}
}
so the created field I want to convert into a Unix timestamp. Any suggestions?
This is how I do it in the frontend:-
const { DateTime } = require('luxon')
module.exports.getMongoTimestamp = timestamp => {
const timeStampArgs = timestamp.toString().split(' ')
const timestampUnix = DateTime.fromRFC2822(`${timeStampArgs[0]}, ${timeStampArgs[2]} ${timeStampArgs[1]} ${timeStampArgs[3]} ${timeStampArgs[4]} ${timeStampArgs[5].replace('GMT', '')}`).toMillis()
return parseInt(timestampUnix, 10)
}
I am using luxon to do it!