我有两个具有重复created
和modified
属性的模式。 mongodb中有没有办法重复使用它而不是一遍又一遍地重复相同的代码?似乎找不到谷歌搜索这个的正确短语。
管理架构
import mongoose from 'mongoose';
const AdminSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
companyId: {
id: mongoose.Schema.Types.ObjectId,
ref: 'Company',
},
created: {
at: {
type: Date,
default: Date.now,
},
by: String,
},
modified: {
at: {
type: Date,
default: Date.now,
},
by: String,
},
});
export default mongoose.model('Admin', AdminSchema);
AdminPermissions Schema
import mongoose from 'mongoose';
const AdminPermissionsSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
companyId: {
id: mongoose.Schema.Types.ObjectId,
ref: 'Company',
},
label: String,
description: String,
created: {
at: {
type: Date,
default: Date.now,
},
by: String,
},
modified: {
at: {
type: Date,
default: Date.now,
},
by: String,
},
});
export default mongoose.model('AdminPermissions', AdminPermissionsSchema);
答案 0 :(得分:2)
Mongoose为您提供了在使用createdAt
和updatedAt
属性创建或更新期间时间戳您的文档的选项。这样做而不是使用created
和modified
,
const AdminSchema = new mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
companyId: {
id: mongoose.Schema.Types.ObjectId,
ref: 'Company',
},
createdBy: String,
modifiedBy: String,
}, {timestamps: true}); //this is required
export default mongoose.model('Admin', AdminSchema);
分别处理createdBy
和modifiedBy
。您可以为所有模式声明添加时间戳,如上所述。