我已经构建了一个架构如下:
const UserInfoSchema = new Schema({
email: { type: String, required: true, unique: true },
username: { type: String, required: true, unique: true },
userId: { type: Schema.Types.ObjectId, ref: 'User'},
displayName: { type: String, required: true },
profilePic: {
filename: {type: String},
url: {type: String}
},
created_at: Date,
updated_at: Date
})
我这里需要的是email, username 和userId 等字段一旦保存,就不应该被修改。是否有针对此类功能的预构建 Mongoose ?
我对 schema.pre('update', (next) => {})
做了一些研究,但没有得到任何真正有用的东西/不知道是否可以用于上述特征。非常感谢对此事的任何帮助。提前致谢。
最佳答案
还有更简单的方法 当你保存 Schema 时,你可以将字段设置为不可变的,就像这样
const UserInfoSchema = new Schema({
email: { type: String, required: true, unique: true, immutable:true },
username: { type: String, required: true, unique: true, immutable:true },
userId: { type: Schema.Types.ObjectId, ref: 'User', immutable:true},
displayName: { type: String, required: true },
profilePic: {
filename: {type: String},
url: {type: String}
},
created_at: Date,
updated_at: Date
})
它不会抛出任何错误,如果你想要它你应该在别处检查它,但是当你试图修改不可变字段时,它根本不会改变
关于node.js - 一旦保存在 Mongoose 中,如何使某些字段不可更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43488493/