Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the updatedAt timestamp using mongoose during a data migration

I am doing a data migration from MS SQL to MongoDB. I am using mongoose and in my schema I set the timestamp property to true.

{
  timestamps: true
}

I then try and set the values of the createdAt and updatedAt fields. When inserting a record. The createdAt field saves correctly, however, the updatedAt field is set to whatever the createdAt field is.

Is this the standard behaviour or am I doing something wrong?

like image 207
RedJandal Avatar asked Oct 25 '25 06:10

RedJandal


1 Answers

The timestamps option is really cool, without doubt, but i'm still doing it "old school":

'use strict';
/**
 * Module dependencies
 */
const mongoose = require('mongoose');


var DataSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true, 
        lowercase: true
    }, 
    created: {
        type: Date,
        default: Date.now
    },
    updated: {
        type: Date,
        default: Date.now
    }
});

DataSchema.pre('save', function(next) {
    this.updated = Date.now();
    return next();
});

mongoose.model('Data', DataSchema);
like image 187
Boris Siscanu Avatar answered Oct 26 '25 19:10

Boris Siscanu