创建 REST API 以处理来自 Node.js 和 MongoDB 上不同传感器的 JSON 数据

托尼

我正在尝试制作一个 REST API 来处理来自传感器(温度计、湿度计)的 JSON 数据来存储和处理温度和湿度数据。但是目前,我还没有直接从传感器获取数据,因此我计划通过 http GET/POST 请求从客户端向 node.js 服务器发送虚拟数据。

我使用 Node.js 作为服务器,我正在尝试使用 mongoose 保存到 mongodb。

当尝试使用 mvc 设计模式设计这个系统时,我一开始只尝试制作一个 sensor.model.js 和 sensor.controller.js 但是当我不得不处理两个不同的传感器数据时,问题就出现了,每个数据都发送了它的温度数据或湿度数据。所以我不确定我应该如何设计 API。我认为将每个传感器数据分别发布到例如“localhost:3000/sensors/thermometer/”和“localhost:3000/sensors/hygromometer/”是一个更好的选择。我现在可以成功地将 POST 请求发送到“localhost:3000/sensors/thermometer/”和“localhost:3000/sensors/hygromometer/”,但我希望能够发送 GET 方法来从按 sensor_type 排序的“/sensors”中获取所有数据. 我怎样才能做到这一点?有没有什么好的方法来解决这个问题?

我在下面放置了 sensor.js 和 thermometer.js 的代码。Hydrometer.js 与 thermometer.js 完全相同,所以我懒得说出来。

非常感谢你。

// sensors.model.js

const mongoose = require('mongoose');

const sensorSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    // this method below doesn't work.
    sensor_type: {type: String, ref: 'Hygro'},
    sensor_type: {type: String, ref: 'Thermo'},
    //time : { type : Date, default: Date.now },
    temperature: {type: Number},
    humidity: {type: Number}
});

module.exports = mongoose.model('Sensor', sensorSchema);

//____________________________________________________________________________

// sensors.route.js

router.get('/', (req, res, next) => {
    Sensor.find()
    .select('_id sensor_type temperature humidity')
    .exec()
    .then(docs => {
        res.status(200).json({
          sensors: docs.map(doc => {
            return {
                _id: doc._id,
                sensor_type: doc.sensor_type,
                temperature: doc.temperature,
                humidity: doc.humidity + "%"
                }
          })
        });
    })
    .catch(err => {
        res.status(500).json({
          error : err
        });
    });

//___________________________________________________________________________


// thermometer.model.js

const mongoose = require('mongoose');

const thermoSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    sensor_type: {type: String, required: true},
    temperature: {type: Number, required: true}
});

module.exports = mongoose.model('Thermo', thermoSchema);

//___________________________________________________________________________


// thermometer.route.js

router.post('/', (req, res, next) => {
    // create sensor object
    const thermo = new Thermo({
      _id: new mongoose.Types.ObjectId(),
      sensor_type: req.body.sensor_type,
      temperature: req.body.temperature
    });
    //save thermo obj into the db
    thermo
    .save()
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: 'Created sensor data successfully',
        createdSensor_data: {
          sensor_type: result.sensor_type,
          temperature: result.temperature,
          _id: result._id
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.status(500).json({
          error: err
      });
    });
}
kengres

传感器可以同时存储湿度和温度吗?如果不是,那么设计可能很简单:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const sensorSchema = new Schema({
    _id: Schema.Types.ObjectId,
    type: {
      type: String,
      required: true,
      enum: ['Hydro', 'Thermo']
    },
    //time : { type : Date, default: Date.now },
    // for the time I use mongoose built in { timestamps: true }
    // temperature: {type: Number},
    // humidity: {type: Number}
    // store value instead. if it's type 'Hydro' you know it's humidity
    value: {
      type: Number,
      required: true
    }
}, { timestamps: true } );
// timestamps: true gives you createdAt and updatedAt automatically

module.exports = mongoose.model('Sensor', sensorSchema);

获取所有传感器

// sensors.route.js

router.get('/', (req, res, next) => {
  Sensor.find()
    .select()
    .exec()
    .then(result => {
      res.status(200).json({
        sensors: result.map(item => {
          return item._doc
        })
      });
    })
    .catch(err => {
      res.status(500).json({
        error: err
      });
    });
})

对于发布请求

router.post('/', (req, res, next) => {
  // create sensor object
  const sensor = new Sensor({
    // _id: new mongoose.Types.ObjectId(), 
    // you dont new to add _id, Mongoose adds it by default
    type: req.body.sensor_type,
    value: req.body.temperature
  });
  //save it
  sensor
  .save()
  .then(result => {
    console.log(result);
    res.status(201).json({
      message: 'Created sensor data successfully',
      createdSensor_data: result._doc // you can access the data on the _doc property
    });
  })
  .catch(err => {
    console.log(err);
    res.status(500).json({
        error: err
    });
  });
})

我还会验证req.body数据并在没有错误时抛出错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何自动创建REST API node.js / MongoDB

来自分类Dev

同步来自不同传感器的数据

来自分类Dev

hapi和node.js创建REST API服务器

来自分类Dev

存储和监视以处理流数据(例如来自传感器的数据)吗?

来自分类Dev

Node.js Rest API验证来自URL的传入JSON

来自分类Dev

Node.js:在迭代的JSON POST数据上创建多个MongoDB文档

来自分类Dev

使用 Node Js 和 express 调用来自 rest api 的 post 请求时出错。请求数据变空

来自分类Dev

如何处理来自node.js的网页上的数据

来自分类Dev

如何处理来自node.js的网页上的数据

来自分类Dev

从 Rest api 异步获取数据并使用 node.js 将它们加载到 mongodb - 使用承诺

来自分类Dev

在基于Node.js,Express和MongoDb的REST Api中使用绝对引用

来自分类Dev

Node.js 和 express Rest api 来创建自定义字段路由

来自分类Dev

MongoDB查询传感器数据收集

来自分类Dev

如何使用Node.js MongoDB Express.js创建用于登录和注册的简单静态API

来自分类Dev

创建REST / JSON API

来自分类Dev

使用来自node.js的angularjs中的json数据作为后端和sql db

来自分类Dev

使用mongodb创建数据库node.js

来自分类Dev

将Json数据从角度JS传递到spring REST API并进行处理

来自分类Dev

Hadoop / Cassandra-如何存储和分析来自数千个传感器的数据?

来自分类Dev

Hadoop/Cassandra - 如何存储和分析来自数千个传感器的数据?

来自分类Dev

在PHP中显示来自JSON的单个数组项(NODE.JS和EXPRESS API)

来自分类Dev

Node API 上的 MongoDB ISODate 和时区

来自分类Dev

从MongoDB在Node.Js中创建JSON树

来自分类Dev

使用哪些算法和库来处理传感器数据

来自分类Dev

如何使用 Node.js 在 Azure 上为 Documentdb 数据库构建 Rest API

来自分类Dev

使用Mongoose和Node.js更新MongoDB中的数据

来自分类Dev

如何在 Node Js 和 Mongodb 中监听数据变化

来自分类Dev

如何在Android Wear模拟器上模拟来自心率传感器的数据?

来自分类Dev

将JSON数据从Node.js存储到MongoDB

Related 相关文章

  1. 1

    如何自动创建REST API node.js / MongoDB

  2. 2

    同步来自不同传感器的数据

  3. 3

    hapi和node.js创建REST API服务器

  4. 4

    存储和监视以处理流数据(例如来自传感器的数据)吗?

  5. 5

    Node.js Rest API验证来自URL的传入JSON

  6. 6

    Node.js:在迭代的JSON POST数据上创建多个MongoDB文档

  7. 7

    使用 Node Js 和 express 调用来自 rest api 的 post 请求时出错。请求数据变空

  8. 8

    如何处理来自node.js的网页上的数据

  9. 9

    如何处理来自node.js的网页上的数据

  10. 10

    从 Rest api 异步获取数据并使用 node.js 将它们加载到 mongodb - 使用承诺

  11. 11

    在基于Node.js,Express和MongoDb的REST Api中使用绝对引用

  12. 12

    Node.js 和 express Rest api 来创建自定义字段路由

  13. 13

    MongoDB查询传感器数据收集

  14. 14

    如何使用Node.js MongoDB Express.js创建用于登录和注册的简单静态API

  15. 15

    创建REST / JSON API

  16. 16

    使用来自node.js的angularjs中的json数据作为后端和sql db

  17. 17

    使用mongodb创建数据库node.js

  18. 18

    将Json数据从角度JS传递到spring REST API并进行处理

  19. 19

    Hadoop / Cassandra-如何存储和分析来自数千个传感器的数据?

  20. 20

    Hadoop/Cassandra - 如何存储和分析来自数千个传感器的数据?

  21. 21

    在PHP中显示来自JSON的单个数组项(NODE.JS和EXPRESS API)

  22. 22

    Node API 上的 MongoDB ISODate 和时区

  23. 23

    从MongoDB在Node.Js中创建JSON树

  24. 24

    使用哪些算法和库来处理传感器数据

  25. 25

    如何使用 Node.js 在 Azure 上为 Documentdb 数据库构建 Rest API

  26. 26

    使用Mongoose和Node.js更新MongoDB中的数据

  27. 27

    如何在 Node Js 和 Mongodb 中监听数据变化

  28. 28

    如何在Android Wear模拟器上模拟来自心率传感器的数据?

  29. 29

    将JSON数据从Node.js存储到MongoDB

热门标签

归档