【问题标题】:Inserting a document into an collection of mongodb database via node.js通过 node.js 将文档插入到 mongodb 数据库的集合中
【发布时间】:2012-12-20 11:53:48
【问题描述】:

我有一个使用 node.js、express 和串行端口编写的小型 Web 服务器,它会不断地监听通过 USB 连接到 mac 的温度传感器。代码如下:

var serialport = require("serialport"),       // include the serialport library
    SerialPort  = serialport.SerialPort,      // make a local instance of serial
    app = require('express')(),           // start Express framework
    server = require('http').createServer(app),   // start an HTTP server
    io = require('socket.io').listen(server);   // filter the server using socket.io

var mongo = require('mongodb');

var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('sensordatabase', server);

db.open(function(err, db) {
  if(!err) {
    console.log("Connected to 'sensordatabase' database");
    db.collection('tempsensor', {safe:true}, function(err, collection) {
      if (err) {
        console.log("The 'values' collection doesn't exist. Creating it with sample data...");
      }
    });
  }
});

var serialData = {};                // object to hold what goes out to the client
server.listen(8080);                // listen for incoming requests on the server
console.log("Listening for new clients on port 8080");

// open the serial port. Change the name to the name of your port, just like in Processing and Arduino:
var myPort = new SerialPort("/dev/cu.usbmodem5d11", { 
// look for return and newline at the end of each data packet:
  parser: serialport.parsers.readline("\r\n") 
});

// respond to web GET requests with the index.html page:
app.get('/', function (request, response) {
  myPort.on('data', function (data) {
    // set the value property of scores to the serial string:
    serialData.value = data;
    response.send(data);
    // for debugging, you should see this in Terminal:
    console.log(data);
  });
});

从上面的代码可以看出,我的传感器值存储在“数据”中。

现在我想将此数据保存到具有以下格式的温度传感器集合中:

{
    "Physicalentity": "Temperature",
    "Unit": "Celsius",
    "value": "",
    "time": "",
    "date": ""
  },

我的问题是:

1:如何使用 node.js 的 mongodb 驱动程序将“数据”保存在值对象中? 2:自动添加数据的时间如何添加?

我知道有一个名为 new Date() 的函数用于日期,是否有类似的时间函数?

非常感谢任何帮助。

非常感谢。

【问题讨论】:

    标签: node.js mongodb insert node-mongodb-native


    【解决方案1】:

    您可以执行类似的操作将文档插入您的集合中。

    db.collection('tempsensor',{safe:true}, function(err, collection) {
    
    collection.insert({
    "Physicalentity": "Temperature",
    "Unit": "Celsius",
    "value": "",
    "time": "",
    "date": ""
    }, function(err, doc) {
      if(err){
         console.log("Error on document insert");
      }else{
         //Document saved succesfuly
         }
      });
    });
    

    【讨论】:

    • 如何将变量数据插入到对象值中?
    【解决方案2】:
    > db.c.insert({'date': new Date(), 'time_hours': new Date().getHours(), 'time_mi
    n': new Date().getMinutes()})
    Inserted 1 record(s) in 31ms
    > db.c.find({})
    { "_id" : ObjectId("50d30884059dc377c6ff66ec"), "date" : ISODate("2012-12-20T12:
    45:56.493Z"), "time_hours" : 16, "time_min" : 45 }
    Fetched 1 record(s) in 0ms
    >
    

    使用 Mongo shell。这意味着您可以在任何 mongo 驱动程序中使用它。

    【讨论】:

      【解决方案3】:

      请记住 - 这不是学习教程的地方,这是人们遇到与他们的学习能力无关的技术或软件问题的地方。为了改善这一点,请阅读使用 mongodb 和整体使用 node.js 的示例。

      以下是一些关于您的情况的详细信息,可以为您提供指导:

      在 myPort.on('data') 的回调函数中,您可以访问您的数据,这正是您必须将数据保存到数据库的地方。

      同时,当您初始化数据库连接和集合时,您需要获取集合的句柄以便之后在应用程序中使用它。 在 db.collection('tempsensor') 的回调函数中,您有对象集合 - 这是您执行 mongodb 函数以处理该集合中的数据所需要的。

      所以将此变量保存在共享范围内的某处(可以是全局变量或集合数组)。

      然后在收到数据的回调中,使用此集合并按照 Serdar Dogruyol 的建议传递数据。

      【讨论】:

        猜你喜欢
        • 2013-01-02
        • 2016-09-22
        • 2015-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-04
        • 1970-01-01
        • 2016-02-22
        相关资源
        最近更新 更多