I am a newbie learner to MERN stack, in my server side I created a createRecord function as below:
export const createRecord = async (req, res) => {
const { person_name, person_position, person_level } = req.body;
const newRecordItem = new RecordItem({
person_name,
person_position,
person_level,
});
As I understand, newRecordItem makes a RecordItem object which is a mongoose model as below:
const itemSchema = mongoose.Schema({
person_name: String,
person_position: String,
person_level: String,
createdAt: {
type: Date,
default: new Date(), //this only returns one specific time which is server start time
},
});
var RecordItem = mongoose.model("recorditem", itemSchema);
In this structure, when I create a new record its created_At variable always returns when server is up time for new created records not when actually created.
My solution to this, simply sending Date value in createRecord function and removing default Date value in schema. But why schema only returns one time value at the first structure above.
This works as intended:
export const createRecord = async (req, res) => {
const { person_name, person_position, person_level } = req.body;
const createdAt = new Date();
const newRecordItem = new RecordItem({
person_name,
person_position,
person_level,
createdAt,
});
And the schema:
const itemSchema = mongoose.Schema({
person_name: String,
person_position: String,
person_level: String,
createdAt: Date,
});
Try to use timestamps
in your schema after defining you fields.
const itemSchema = mongoose.Schema({
person_name: String,
person_position: String,
person_level: String,
},{timestamps:true});
var RecordItem = mongoose.model("recorditem", itemSchema);