node.js - 提供所需值时如何修复 mongoose 验证器错误,但 mongoose 无法识别
问题描述
我正在将文档保存到 mongoDB,但我收到一个验证器错误,提示“ValidatorError: Path properties.chargeBoxIdentity
is 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));
解决方案
这只是您的语法中的一个小错误,请将这些行更改为:
const HB = new HeartbeatModel({
properties: {chargeBoxIdentity: 12345}
});
推荐阅读
- c++ - C++中关于函数指针的练习
- python - 如何检查文本框 Tkinter Python 中的输入?
- javascript - 手动将 setTimeout 添加到谷歌标签管理器
- swift - 小部件不断在设备屏幕上重新加载
- android - android 5 和 5.1 中的矢量可绘制资源未找到错误
- java - 如何显示输入数字(质数)的 2 位总和
- python - Discord.py 特权意图停止 on_message 和命令工作
- python - 根据 Pandas 数据框列中的值创建包含指定范围的新列
- html - 从本地磁盘到本地磁盘的跨源错误(仅限基本 HTML,不是 AJAX)
- django - Django 序列化程序过滤外键