Node.js Mongoose仅使用createdAt时间戳
我在mongoose中有以下消息模式:Node.js Mongoose仅使用createdAt时间戳,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在mongoose中有以下消息模式: var messageSchema = mongoose.Schema({ userID: { type: ObjectId, required: true, ref: 'User' }, text: { type: String, required: true } }, { timestamps: true }); 是否仍然可以忽略updatedAt时间戳?消息不会更新,因此updatedAt将浪费空间编辑我已修改了答案,以反映更好的选
var messageSchema = mongoose.Schema({
userID: { type: ObjectId, required: true, ref: 'User' },
text: { type: String, required: true }
},
{
timestamps: true
});
是否仍然可以忽略updatedAt时间戳?消息不会更新,因此updatedAt将浪费空间编辑我已修改了答案,以反映更好的选项,以便按照@JohnnyHK使用默认值 您可以通过在模式中声明
createdAt
(或您想称之为的任何名称)来自行处理此问题:
mongoose.Schema({
created: { type: Date, default: Date.now }
...
或者,我们也可以在预保存挂钩中更新新文档的值:
messageSchema.pre('save', function (next) {
if (!this.created) this.created = new Date;
next();
})
沿着这些线还有一个标志,您可以使用它来检查文档是否是新的
messageSchema.pre('save', function (next) {
if (this.isNew) this.created = new Date;
next();
})
较旧的主题,但根据您的模式,可能有更好的选项。。。 如果您坚持使用默认的mongodb/mongoose自动生成id,那么已经内置了一个时间戳。如果你所需要的只是“创建”而不是“更新”,那么就使用 文档。_id.getTimestamp() 从这里的MongoDB文档。。。
在这里 使用Mongoose v5可能更好的方法是:
const schema = new Schema({
// Your schema...
}, {
timestamps: { createdAt: true, updatedAt: false }
})
Mongoose时间戳接口具有这些可选字段
interface SchemaTimestampsConfig {
createdAt?: boolean | string;
updatedAt?: boolean | string;
currentTime?: () => (Date | number);
}
我们可以传递所需字段的布尔值(createdAt:true
和updatedAt:true
将添加这两个字段)。
我们可以使用currentTime函数覆盖日期格式
例如:
import mongoose from 'mongoose';
const { Schema } = mongoose;
const annotationType = ['NOTES', 'COMMENTS'];
const referenceType = ['TASKS', 'NOTES'];
const AnnotationSchema = new Schema(
{
sellerOrgId: {
type: String,
required: true,
},
createdById: {
type: String,
required: true,
},
annotationType: {
type: String,
enum: annotationType,
},
reference: {
id: { type: String, index: true },
type: {
type: String,
enum: referenceType,
},
},
data: Schema.Types.Mixed,
},
{ timestamps: { createdAt: true },
);
const AnnotationModel = mongoose.models.annotation || mongoose.model('annotation', AnnotationSchema);
export { AnnotationModel, AnnotationSchema };
如果您定义了默认值:
created:{type:Date,default:Date.now}
Yes,则可以跳过中间件。我的错。我已经从默认设置中得到了奇怪的不必要的影响,我现在明确地写出来了,但在这种情况下,它要好得多。