node.js - Mongoose 模式没有选择新属性

标签 node.js mongodb mongoose

我有这个 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 服务器,但这并没有做任何事情。

最佳答案

在任何情况下,如果您保存您的用户模型,MongoDB 中显示的具有实际值的字段将是您在保存模型时为自己设置的值或在您的 userSchema 中设置默认值的字段。

所以,澄清一下:

    address: { type: String, default: ' ' } 

除非您在保存用户模型时设置特定地址,否则将在 MongoDB 中显示值为 ' '。

但是,

    address: String

不会显示在 MongoDB 中,除非您在保存用户模型时设置了特定地址。

编辑 感谢 Matthew 指出,实际上 upsert 行为确实如下:

If upsert is true and no document matches the query criteria, update() inserts a single document.

关于node.js - Mongoose 模式没有选择新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31755369/

相关文章:

javascript - Lodash 根据键对对象列表进行排序

mysql - 使用 Node js 从 mysql 中选择查询(LIKE 查询)

执行大量写入时 MongoDB 光标超时

javascript - 如何将数组从 html 发送到 node.js,然后再发送到 mongodb?

node.js - $lookup 查找子数组中的每个元素

javascript - Node JS - 使用路由器添加更多页面(ejs 模板)

javascript - 在 if-else 中看不到 process.env.NODE_ENV

python - 在 Python 中从 MongoDB GridFS 加载 Spark 2.x DataFrame

node.js - Node , Mongoose : on save() "VersionError: No matching document found."

javascript - 使用 .find() 的 Mongoose 静态函数返回查询,并且静态函数无法识别