首页 > 解决方案 > 提供所需值时如何修复 mongoose 验证器错误,但 mongoose 无法识别

问题描述

我正在将文档保存到 mongoDB,但我收到一个验证器错误,提示“ValidatorError: Path properties.chargeBoxIdentityis required”。

我有一个工作正常的不同文件。我已经复制并粘贴并修改了它,但这个 Heartbeat 文档无法正常工作。

我试图将chargeBoxIdentity 值“硬编码”到文档中,但这不起作用。我在模式中设置了一个硬编码的默认值,就像日期一样,并且确实有效,但这对于我的用例来说并不理想,因为每个充电器都有不同的身份。

const HeartbeatSchema = mongoose.Schema({
    properties: {
        time : { type : Date, default: Date.now },
        chargeBoxIdentity : { type: Number, required: true}
    },
    additionalProperties: false
})

module.exports = mongoose.model('Heartbeat', HeartbeatSchema)


// Here I set chargeBox Identity as 12345, but I get an error that properties.chargeBoxIdentity is required and won't save the document

const HB = new HeartbeatModel({
          chargeBoxIdentity: 12345

        });

  HB.save()
        .then(result => {console.log(result)})
        .catch(err => console.log(err));

标签: node.jsmongodbmongoose

解决方案


这只是您的语法中的一个小错误,请将这些行更改为:

const HB = new HeartbeatModel({
          properties: {chargeBoxIdentity: 12345}
        });

推荐阅读