【发布时间】:2021-10-28 02:13:39
【问题描述】:
如果设置了环境变量TEST,我想从外部test_data.json 文件加载JSON 数据。我能够加载 JSON 对象,但我很难将其转换为以前创建的 Mongoose 模型。我的模型:
const mongoose = require('mongoose');
const SensorSchema = require('./sensor');
const DataEntrySchema = new mongoose.Schema({
datetime: { type: Date, required: true },
sensor: { type: SensorSchema, required: true },
value: { type: Number, required: true }
});
const DataEntry = mongoose.model('DataEntry', DataEntrySchema);
module.exports = DataEntry;
Node.js 服务器代码:
mongoose.connect("mongodb://127.0.0.1:27017/",{
useCreateIndex:true,
useNewUrlParser: true,
useUnifiedTopology: true}
).then(() => {
console.log('Database Successfully Connected')
if(fill_default_data) {
var obj = DataEntry( JSON.parse(fs.readFileSync(path.resolve(__dirname, 'test_data.json'), 'utf8')) );
obj.save();
}
}, error => {
console.log(error)
}
);
test_data.json的内容:
[
{
"id": 1337,
"datetime": "28/08/2021 16:01",
"sensor": {
"id": 123,
"type": "Temperaure"
},
"value": 2502
}
]
但这失败并显示错误消息:
(node:13676) UnhandledPromiseRejectionWarning: ValidationError: DataEntry 验证失败:值:需要路径
value。,传感器: 路径sensor为必填项。日期时间:路径datetime为必填项。
任何提示我可以如何做到这一点?
【问题讨论】: