Reputation: 171
When i update mongodb data, it only shows if I restart the server (triggered by updating a file).
I have tried a number of methods & found others with similar problems, but no answers that I can understand. i.e. How to auto restart node server when update mongodb I get that I don't want to restart the server, but that's when the data updates.
const http = require('http');
const MongoClient = require('mongodb').MongoClient;
const hostname = 'localhost';
const port = 3000;
let dbResponse = 'nothing';
let statsDB; //save db connection
// Connect to the db
MongoClient.connect("mongodb://adminMongo:XXXX@localhost:12345", function (err, db) {
statsDB = db.db('stats');
//databse Insert/Update/Query code here..
if(!err){
statsDB.collection('stats').find().toArray(function(err, docs){
dbResponse = docs;
//db.close();
});
}else{
dbResponse = err;
}
});
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
//nodejs router
let url = require('url').parse(req.url, true);
if(url.pathname ==='/mongo'){
res.end(`${JSON.stringify(dbResponse)}\n`); //this works
}else if(url.pathname ==='/mongo/update'){
dbUpdate(url.query.data_category, url.query.data_end);
}else{
res.end(`${JSON.stringify(dbResponse)}\n`); //this works
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
/* datbase functions */
//not set up as a route yet...
function dbInsert(dataCategory, dataTitle, dataStart, dataEnd, dataInterval){
var doc = {data_category:dataCategory,
data_title:dataTitle,
data_start: dataStart,
data_end: dataEnd,
data_interval: dataInterval};
// insert document to 'users' collection using insertOne
statsDB.collection('stats').insertOne(doc, function(err, res) {
if(err) throw err;
console.log("Document inserted");
// close the connection to db when you are done with it
});
}
function dbUpdate(dataCategory, dataEnd){
MongoClient.connect("mongodb://adminMongo:XXXX@localhost:12345", function (err, db) {
statsDB = db.db('stats');
//dbResponse = JSON.stringify(statsDB);
//if(err) throw err;
//Write databse Insert/Update/Query code here..
if(!err){
//dbResponse.push({'params': dataEnd});
statsDB.collection('stats').updateOne(
{ data_category: dataCategory },
{
$set: {data_end: dataEnd}
},{multi:true}
)
}else{
dbResponse = err;
}
});
}
//dbUpdate('games-won', '5');
function dbDelete(dataCategory){
statsDB.collection('stats').deleteOne({data_category: dataCategory});
//statsDB.collection('stats').deleteMany({data_category: 'toenails-lost'});
if(err) throw err;
}
Once updated the data should be updated without needing to restart the server.
Upvotes: 1
Views: 1005
Reputation: 43
Try the script with one connection to the database when the server starts and everything runs off that connection.
So you'll only have one MongoClient.connect
when the app listens rather that for each query
const url = "mongodb://adminMongo:XXXX@localhost:12345";
// outline the options for mongo db connection
const mongoOptions = { useUnifiedTopology: true };
// create a new mongo client to connect to the database
const client = new MongoClient(url, mongoOptions);
// connect to mongodb database on start of server
client.connect(function(err) {
if (err) {
console.log('Unable to connect to the MongoDB database');
// exit the process if a connection to the database cannot be made
process.exit(1);
} else {
// create local host server
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
}
});
Then when you want to query the database you dont need to open a new connection
eg. this function should work with no need to connect
function dbInsert(dataCategory, dataTitle, dataStart, dataEnd, dataInterval){
var doc = {data_category:dataCategory,
data_title:dataTitle,
data_start: dataStart,
data_end: dataEnd,
data_interval: dataInterval};
// insert document to 'users' collection using insertOne
statsDB.collection('stats').insertOne(doc, function(err, res) {
if(err) throw err;
console.log("Document inserted");
});
}
Upvotes: 1