如何在数据迁移期间使用 mongoose 设置 UpdatedAt 时间戳

Red*_*dal 4 mongoose node.js

我正在进行从 MS SQL 到 MongoDB 的数据迁移。我正在使用猫鼬,并在我的架构中将时间戳属性设置为 true。

{
  timestamps: true
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试设置createdAt和updatedAt字段的值。插入记录时。createdAt 字段保存正确,但是,updatedAt 字段设置为createdAt 字段的值。

这是标准行为还是我做错了什么?

Bor*_*anu 5

毫无疑问,时间戳选项真的很酷,但我仍然在“老派”做:

'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);
Run Code Online (Sandbox Code Playgroud)