如何在数据迁移期间使用 mongoose 设置 updatedAt 时间戳 [英] How do I set the updatedAt timestamp using mongoose during a data migration
问题描述
我正在将数据从 MS SQL 迁移到 MongoDB.我正在使用猫鼬,并在我的架构中将时间戳属性设置为 true.
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
}
然后我尝试设置 createdAt 和 updatedAt 字段的值.插入记录时.createdAt 字段保存正确,但是,updatedAt 字段设置为 createdAt 字段的任何值.
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?
推荐答案
时间戳选项真的很酷,毫无疑问,但我仍然在做老派":
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);
这篇关于如何在数据迁移期间使用 mongoose 设置 updatedAt 时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!