Abhinav Jain
Abhinav Jain

Reputation: 339

How to manually set createdAt timestamp in mongoDB using mongoose?

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
        });

Upvotes: 5

Views: 19562

Answers (2)

Kalana Demel
Kalana Demel

Reputation: 3266

The issue is that your schema does not contain createdAt field, mongoose by default saves data with the strict option enabled where if your schema does not contain a field you cannot add a new one to it Docs. Therefore you first need to add the createdAt field to your schema, following is just an example.

 createdAt: {type: Date, default: Date.now}

After adding this as a field your query should work without issues.

Upvotes: 1

Ashok
Ashok

Reputation: 2932

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() } });
});

Upvotes: 9

Related Questions