Hey y’all,
Is there a way to change the ‘date’ property values of my object when I use the res.json function? Here is my data:
"count":3,"log":
{"_id":"5e4b1dfa1d021a11bd6174b4","userid":"5e4b1dbb739df6104e1c913e","description":"asd","duration":3,"date":"1199145600000"}]}
I want the res.json to return a date string with new Date('object.date').toDateString
but keep the timestamp in the database the same. An example would be:
"date":"Mon Jan 01 2018"}
Project: https://glitch.com/edit/#!/exercise-tracker-stefansen
Thank you!
Hi bstefansen,
i am not sure if i get it right.
But - maybe - there is a way to do so.
File ./server.js
...
userModel.findOne({ _id: req.body.userid }, (err, dataCheck) => {
if (dataCheck === undefined) {
res.send("unknown _id");
} else if (isNaN(req.body.duration) === true) {
res.send("duration is not a number");
} else {
dataExercise.save(function(err) {
if (err) return console.error(err);
});
userModel.findOne({ _id: req.body.userid }, (err, dataUser) => {
/// insert new code here and make use of transformation!!///
let nwDataExercise = dataExercise.toObject({ transform: true });
//////////////////////////////////////////////////////////////////////////////////
return res.json({ username: dataUser.username, nwDataExercise });
});
}
});
...
File model/exercise.js
...
const newExercise = new Schema(
{
userid: String,
description: String,
duration: Number,
date: {// some extra spice to your SchemaType ;)
type: String,
index: true,
transform: v => { // here you can transform the output!
let date = dateFromObjectId(v).toString();
return date.slice(0, date.indexOf("G")); // you can try other functions - everything that meets your needs ;)
}
}
},
{
versionKey: false
}
);
function dateFromObjectId(objectId) { // https://steveridout.github.io/mongo-object-time/
return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
}
...
Read this my friend https://mongoosejs.com/docs/api.html#schematypeoptions_SchemaTypeOptions-transform
I hope this is helpful
1 Like