我有这个mongoose架构,我添加了updated_by和created_by,但出于某种原因,当我将模型从客户端保存到服务器时,这些字段是不可见的:
userSchema = mongoose.Schema({
role: {
type: String,
enum: ['Admin', 'Owner', 'User']
},
username: {
type: String,
unique: true,
required: true,
validate: [validation.usernameValidator, 'not a valid username']
},
passwordHash: {
type: String,
required: true,
validate: [validation.passwordValidator, 'not a valid password']
},
email: {
type: String,
unique: true,
required: true,
validate: [validation.emailValidator, 'not a valid email address']
},
firstName: {
type: String,
required: false
},
lastName: {
type: String,
required: false
},
registered_at: {
type: Date,
default: Date.now
},
created_by: {
type: String,
required: false
},
updated_by: {
type: String,
required: false
},
created_at: {
type: Date,
default: Date.now
},
updated_at: {
type: Date,
default: Date.now
}
},
{
autoIndex: false
});
这通常是个问题吗?我是否必须以某种方式使用Mongoose或MongoDB重建某些东西才能让他们在这个模型上获取新属性?
当然,我确实重新启动了mongoDB服务器,但那并没有做任何事情。
答案 0 :(得分:1)
在任何情况下,如果您保存用户模型,MongoDB中显示的具有实际值的字段将是您在保存模型时为自己设置值的字段,或者是在userSchema中设置默认值的字段。
所以,只是澄清一下:
address: { type: String, default: ' ' }
除非您在保存用户模型时设置特定地址,否则将显示在MongoDB中,值为''。
但是,
address: String
除非您在保存用户模型时设置了特定地址,否则将 NOT 显示在MongoDB中。
修改强> 感谢Matthew指出它,实际上upsert行为确实如下:
如果upsert为true且没有文档符合查询条件,则update()会插入单个文档。