Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在mongoose中保存后,如何使某些字段不可更新?_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 在mongoose中保存后,如何使某些字段不可更新?

Node.js 在mongoose中保存后,如何使某些字段不可更新?,node.js,mongodb,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: { ty

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

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
})
这里我需要的是,一旦电子邮件、用户名和用户ID等字段被保存,就不应该修改。mongoose中有没有为这种功能预先构建的东西

我对schema.pre('update',(next)=>{})做了一些研究,但没有得到任何真正有用的东西/不知道是否可以用于上述功能。在此问题上的任何帮助都将不胜感激。提前谢谢。

有一个更简单的方法
for(const key in userUpdates) {
    switch(key)  { 
        case 'username':
        case 'email':
            throw new Error('These field/s cannot be changed anymore');
    }
}
User.findByIdAndUpdate(id, userUpdates, { new: true, runValidators: true });
保存模式时,可以将字段设置为不可变,如下所示

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


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

我不知道你的情况,但即使所有者仍然无法编辑他们的电子邮件?@thelonglqd让我们不要深入研究我的应用程序的功能。我认为答案与我在我的应用程序中为用户提供的功能没有任何关联。我不认为有关联。例如,有多种方法可以更新文档,但并不总是调用
pre
hook。无论如何,您不能确保只更新代码中需要的字段,例如使用
$set
?这将是一个很好的例子,例如,在模式中使用
冻结
。@Mikey我已经确保更新不会像你说的那样获得数据。但是,我很好奇mongoose/mongodb是否会提供这样的特性。谢谢你的评论。