Reputation: 61
currently i have data that needs to be inserted to mongodb. The data have been successfully inserted into mongodb, however there is some value that i would like to add to the data and append it into mongodb.
How can i do so? This is my code for inserting data
into mongodb
var MongoClient = require('mongodb').MongoClient
, format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
var collection = db.collection('test_insert');
collection.insert({ values:parsestring() }, function(err, docs) {
collection.count(function(err, count) {
console.log(format("count = %s", count));
});
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
console.dir(results);
// Let's close the db
db.close();
});
});
// "1,61,54,87,20,12/3/2016,8:39AM" this default value
function parsestring(str="1,30,40,50,20,10/10/2016,10:39AM")
{
return str.split(",");
}
I would like to add value to the text string.
For example: Machine Unit: 1,
Air Temperature °C: 30,
Water Temperature °C: 40,
Heat Temperature °C: 50,
Room Temperature °C: 20,
Date: 10/10/2016,
Time: 10:39AM
Upvotes: 1
Views: 725
Reputation: 5867
Like already mentioned in the comments, you should store your data as objects (or arrays). The line str.split(",")
already returns you an array, which you store. In your code you also fetch your data as an Array. When you console.dir() your results, you could map your results.entries to a specific output string if you prefer.
collection.find().toArray(function(err, results) {
console.dir(results); // <= results.entries
// Let's close the db
db.close();
});
See also: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/map & https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/entries
However, if you want to store objects (e.g. for accessing data via identifier) you could simply do it like:
function parsestring(str="1,30,40,50,20,10/10/2016,10:39AM"){
var dataArr = str.split(",");
var dbEntry = {};
dbEntry.machine = dataArr[0];
dbEntry.airTemp = dataArr[1];
dbEntry.waterTemp = dataArr[2];
dbEntry.heatTemp = dataArr[3];
dbEntry.roomTemp = dataArr[4];
dbEntry.date = dataArr[5];
dbEntry.time = dataArr[6];
return dbEntry;
}
When returning a simple object from mongoDB, you won't need .toArray()
Upvotes: 1