首页 > 解决方案 > Mongoose:尝试将嵌套对象字段设置为原始值“null”

问题描述

我有一个带有嵌套字段的架构,例如

// model.js
module.exports = Mongoose.model('Model', new Mongoose.Schema(
    {
        Top: {
            Middle: {
                Bottom: Number
            }
        }
    },
    {
        strict: 'throw'
    })
)

所有这些字段都存在是非常罕见的,当一个字段不存在时,生成它的进程会写入null. 我想将严格模式设置为,true但它似乎不喜欢应该包含 Object 的字段而不是包含null

// app.js
const Model = require('./model');
router.post('/api' , async (req, res) => {
    const doc = new Model(req.body);
    const result = await doc.save();
    res.json(result);
})

// test
axios.post('/api', { Top: { Middle: null }})
=> ObjectExpectedError: Tried to set nested object field 'Middle' to primitive value 'null' and strict mode is set to throw.

有没有办法规避这种行为?不幸的是,让生成数据的过程undefined代替null.

标签: node.jsmongodbmongoose

解决方案


推荐阅读