我有一个使用node.js编写的小型web服务器,它可以不断地通过USB监听连接到mac的温度传感器。代码如下:通过node.js将文档插入到mongodb数据库集合中
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()
的函数,对于时间有没有类似的函数?
我真的很感激任何帮助。
感谢提前一吨。
我将如何将变量数据插入对象值? – Spaniard89