我有一個使用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