I am trying to migrate my DB by adding timestamps to all the rows which were missing timestamps earlier. I have calculated createdAt timestamp using _id but I'm not able to set the timestamp. What am I doing wrong here?
Can someone help?
let Question = db.model('Question');
let items = await Question.findWithDeleted();
let processedIds = items.map((q) => q._id);
processedIds.forEach(function (id) {
const timestamp = id.getTimestamp();
// const date = new Date(parseInt(timestamp, 16) * 1000);
// echo(timestamp)
Question.update({ "_id": id }, { "$set": { createdAt: timestamp } }, (h) => {
console.log(h);
});
});
Here is the model:
const Question = new Schema({ "type": { type: String, trim: true, enum: Object.values(questionTypes), required: 'Question type is required' }, "text": { type: String, required: true }, "desc": NotRequiredStringSchema, "options": [{ "id": ObjectId, "name": NotRequiredStringSchema, "helperText": NotRequiredStringSchema, "icon_key": NotRequiredStringSchema, "icon_url": NotRequiredStringSchema, "icon_svg": NotRequiredStringSchema }], "placeHolder": NotRequiredStringSchema, "buttonPosition": NotRequiredStringSchema, "buttonText": NotRequiredStringSchema, "buttonHoverText": NotRequiredStringSchema, "helperText": NotRequiredStringSchema, "max": Number, "min": Number, "default": Mixed, "icon_key": NotRequiredStringSchema, "icon_url": NotRequiredStringSchema, "icon_svg": NotRequiredStringSchema, "showTick": { type: Boolean, required: false, default: false }, "lang": { required: true, type: Map, of: { type: Map, of: String } } }, { timestamps: true });
Best Answer
If you make you schema like this
It will create createdAt and updatedAt field automatically and also update their values on every time on performing create and update operation.
Now other cases if you create manually createdAt and updatedAt fields like this schema
Then you can use middleware for update createdAt and updatedAt value on creating and updating Records.