【问题标题】:Load default data from external .json-file and store into MongoDB从外部 .json 文件加载默认数据并存储到 MongoDB
【发布时间】: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 为必填项。

任何提示我可以如何做到这一点?

【问题讨论】:

    标签: node.js json mongodb


    【解决方案1】:

    您的问题是您没有保存单个 DataEntry 实体,而是尝试保存它们的整个数组。

    记录返回的内容:

    const items = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'test_data.json'), 'utf8')) 
    

    要么循环遍历数组,要么单独保存 DataEntry 项。或者使用批量加载选项:

    DataEntry.create(items)...
    

    以上物品。

    【讨论】:

    猜你喜欢
    • 2020-02-21
    • 2014-02-22
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多