Node.js Mongoose:尝试将嵌套对象字段设置为原始值';空';
我有一个嵌套字段的模式,例如Node.js Mongoose:尝试将嵌套对象字段设置为原始值';空';,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个嵌套字段的模式,例如 // model.js module.exports = Mongoose.model('Model', new Mongoose.Schema( { Top: { Middle: { Bottom: Number } } }, { strict: 'throw' }) ) 所有这些字段都存在是非常罕见的,
// model.js
module.exports = Mongoose.model('Model', new Mongoose.Schema(
{
Top: {
Middle: {
Bottom: Number
}
}
},
{
strict: 'throw'
})
)
所有这些字段都存在是非常罕见的,当一个字段不存在时,生成它的进程写入null
。我希望将strict mode设置为true
,但似乎不希望应该包含对象的字段包含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
不是一个简单的选择。请共享您的插入/更新代码。您可以设置{}而不是null。添加一些代码来显示基本的express端点,希望这就是您想要的。您可以共享您的model.js代码吗?