首页 > 解决方案 > 物联网数据数组的 mongoose.Schema 并将数据提取到 chart.js

问题描述

首先,我需要一个用于 iotdata 的 mongoose.Schema,其中包含:

  1. 设备ID
  2. 实体类型
  3. 时间戳
  4. 属性有一个键和一个值,例如“键”:“温度”和“值”:12

我写了这个数组,但我不确定,如果它是正确的:

const DataSchema = mongoose.Schema({
    device_id:{
        type: String,
        required: true
    },
    entity_type: {
        type: String,
        required: true
    },
    time: {
        type: Date,
        required: true
    },
    
    attributes:  { type : Array , "default" : []}

});

下一行:

const Data = module.exports = mongoose.model('Data', DataSchema);

之后我想将数据提取到 chart.js 前端是用 Angular 编写的。我在 Angular 中创建了一个服务组件来连接到后端 Node.js Express:

export class DataComponent implements OnInit {
  data: Array<Data> = [];
  data: Data;
  device_id: string;
  entity_type: string;
time: date, 
attributes: array

   
  constructor(private dataService: DataService) { }

  ngOnInit(): void {
    this.DataService.getData().subscribe(
      (data: any) => // set response type to any
      {
        this.data = data;
        console.log(this.data);
      }
    );

  }

}

但我怎样才能将数据提取到chart.j?

var myLineChart = new Chart(ctx, {
    type: 'line',
    data: data,  **-> The data here should be the data from the mongodb**
    options: options
});

标签: node.jsangularmongoosechart.jsmongoose-schema

解决方案


您的模型创建 ID 正确,

您需要创建控制器文件和路由以在 Node JS 中获取数据,发布到您将能够获取数据。请让我知道需要更多帮助


推荐阅读