[英]Inserting a document into an collection of mongodb database via node.js
我有一個使用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()
有一個名為new Date()
的函數,時間是否有類似的函數?
我真的很感謝您的幫助。
在此先感謝一噸。
您可以執行類似的操作以將文檔插入到集合中。
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
}
});
});
> 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驅動程序中使用它。
請記住-這不是學習教程的地方,這里是人們遇到與其學習能力無關的技術或軟件問題的地方。 為了改善這一點,請閱讀使用mongodb的示例以及總體上使用node.js的示例。
以下是一些有關您的情況的詳細信息以指導您:
在myPort.on('data')上的回調函數中,您可以訪問數據,這是您必須將數據保存到數據庫的確切位置。
同時,在初始化數據庫連接和集合時,您需要獲取集合的句柄才能在之后的應用程序中使用它。 在db.collection('tempsensor')的回調函數中,您具有對象集合-這是執行mongodb函數以使用該集合中的數據所需要的。
因此,請將此變量保存在共享作用域中的某個位置(可以是全局變量或集合數組)。
然后在回調收到的數據時,使用此集合並傳遞數據,如Serdar Dogruyol所建議。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.