我有一个使用 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);
});
});
从上面的代码可以看出,我的传感器值存储在“数据”中。
现在我想将此数据保存到我的 tempsensor 集合中,该集合具有以下格式:
{
"Physicalentity": "Temperature",
"Unit": "Celsius",
"value": "",
"time": "",
"date": ""
},
我的问题是:
1:如何使用node.js的mongodb驱动程序将“数据”保存在值对象中?2:如何添加数据自动添加的时间?
我知道有一个调用new Date()
日期的函数,是否有类似的时间函数?
我真的很感激任何帮助。
提前致谢。