0

I would like to load JSON data from external test_data.json file if environment variable TEST is set. I am able to load the JSON object, but I struggle converting it to previously created Mongoose model. My model:

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 server code:

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)
  }
);

Content of test_data.json:

[
    {
        "id": 1337,
        "datetime": "28/08/2021 16:01",
        "sensor": {
            "id": 123,
            "type": "Temperaure"
        },
        "value": 2502
    }
]

But this fails with error message :

(node:13676) UnhandledPromiseRejectionWarning: ValidationError: DataEntry validation failed: value: Path value is required., sensor: Path sensor is required., datetime: Path datetime is required.

Any tips how I can do this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
binaryBigInt
  • 1,526
  • 2
  • 18
  • 44

1 Answers1

1

Your problem is that you aren't saving an individual DataEntry entity, but trying to save a whole array of them.

Log what comes back from:

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

Either loop through the array and save the DataEntry items individually. Or use the blulk load option:

DataEntry.create(items)...

with the above items.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
  • Thank you! This `populate` also helped me: https://stackoverflow.com/questions/18001478/referencing-another-schema-in-mongoose – binaryBigInt Aug 28 '21 at 18:32