如何使某些字段一旦保存在猫鼬中就不可更新?

Tol*_*see 4 mongoose mongodb node.js

我构建了一个架构,如下所示:

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

我这里需要的是,一旦保存了电子邮件、用户名和用户 ID 等字段,就不应该修改。猫鼬中是否有针对此类功能的预构建内容?

我已经做了一些研究schema.pre('update', (next) => {}),但没有得到任何真正有用的东西/不知道是否可以使用上述功能。非常感谢有关此事的任何帮助。提前致谢。

小智 5

保存 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
})

Run Code Online (Sandbox Code Playgroud)

它不会抛出任何错误,如果你想要它,你应该在其他地方检查它,但是当你尝试修改不可变字段时,它根本不会改变