node.js - 一旦保存在 Mongoose 中,如何使某些字段不可更新?

标签 node.js mongodb mongoose

我已经构建了一个架构如下:

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/

相关文章:

node.js - 无法在 Angular 8 中创建新项目

MongoDB聚合数组文档

javascript - Mongoose 中的保存方法失败

javascript - 如何删除或过滤数组中的特定对象

javascript - 如何使用nodeJS和Puppeteer解决 "Target closed"错误?

mysql - 如何修复 MySQL 中的表大小?

javascript - MONGOOSE - 仅显示我在对象内输入的特定值

node.js - 在 Mongoose 中计算平均值

node.js - MongoDB 设置数据库脚本(基于 NodeJS 的项目)

node.js - 如何使用 firestore 模块化 api 选择特定字段