Node.js – How to manually set createdAt timestamp in mongoDB using mongoose

mongodbmongoosenode.js

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

const SchemaName = new Schema({
 .......
}, {
  timestamps: true
})

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

const SchemaName = new Schema({
 .......
 createdAt: { type: Date, default: Date.now },
 updatedAt: { type: Date, default: Date.now }
})

Then you can use middleware for update createdAt and updatedAt value on creating and updating Records.

SchemaName.post('save', (doc) => {
  console.log('%s has been saved', doc._id);
});

SchemaName.pre('update', () => {
  this.update({},{ $set: { updatedAt: new Date() } });
});