I have a small web server written using node.js, express and serial port which would constantly listen to an temperature sensor attached to the mac via USB. The code is as follow:
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);
});
});
As it can be seen from the above code, my sensor values are stored in "data".
Now I would like to save this data into my tempsensor collection which has the following format:
{
"Physicalentity": "Temperature",
"Unit": "Celsius",
"value": "",
"time": "",
"date": ""
},
My question is:
1: How can I save the "data" in the value object, using the mongodb driver for node.js? 2: How can I add the time when the data is added automatically?
I know there's a function called new Date()
for the date, is there a similar function for time?
I would really appreciate any help.
Thanks a ton in advance.