从JSON文件加载测试数据到MongoDB时如何同步创建Sensor子模块文档
问题原因
- 你在
DataEntrySchema中定义的sensor字段为嵌入式子文档,直接复用SensorSchema作为结构定义,这种设计下传感器数据只会作为DataEntry文档的一部分存储,不会自动写入Sensor模型对应的独立sensors集合 - 现有数据导入逻辑仅调用了
DataEntry.create()写入数据条目,没有触发Sensor模型的写入操作,自然无法查询到独立的Sensor文档
解决方法
如果需要同步创建独立的Sensor文档,可按如下逻辑调整导入代码,先批量插入去重后的传感器数据,再写入数据条目:
mongoose.connect("mongodb://127.0.0.1:27017/",{ useCreateIndex:true, useNewUrlParser: true, useUnifiedTopology: true} ).then(async () => { console.log('Database Successfully Connected') if(fill_default_data) { // 读取原始JSON数据 const rawData = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'test_data.json'), 'utf8')) // 提取所有传感器数据,按sensor.id去重避免重复插入 const uniqueSensors = [...new Map(rawData.map(item => [item.sensor.id, item.sensor])).values()] // 批量创建独立Sensor文档 await Sensor.insertMany(uniqueSensors) // 再创建DataEntry数据条目 await DataEntry.create(rawData) } }, error => { console.log(error) } );
如果后续需要做关联查询,建议将DataEntrySchema的sensor字段改为引用类型,维护起来更灵活:
const DataEntrySchema = new mongoose.Schema({ datetime: { type: String, required: true }, // 改为关联Sensor集合的ObjectId sensor: { type: mongoose.Schema.Types.ObjectId, ref: 'Sensor', required: true }, value: { type: Number, required: true } });
改为引用类型后,导入数据时需要先插入Sensor拿到对应的_id,再赋值给DataEntry的sensor字段,后续查询时调用.populate('sensor')即可自动关联返回完整的传感器信息。
内容的提问来源于stack exchange,提问作者binaryBigInt
相关产品推荐
相关产品推荐

