除非重新启动节点服务器,否则不会显示mongodb更新

时间:2019-07-24 12:59:28

标签: node.js mongodb

当我更新mongodb数据时,它仅在我重新启动服务器时显示(通过更新文件触发)。

我尝试了多种方法并发现了其他具有类似问题的方法,但是没有我能理解的答案。 即How to auto restart node server when update mongodb 我知道我不想重启服务器,但是那是数据更新的时候。

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;

}

更新后,无需重新启动服务器即可更新数据。

1 个答案:

答案 0 :(得分:1)

服务器启动时,尝试使用脚本与数据库建立一个连接,然后一切都在该连接上运行。

因此,当应用程序侦听时,您只有一个MongoClient.connect,而不是每个查询


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}/`);

});
  }
});

然后,当您要查询数据库时,不需要打开新连接

例如该功能无需连接即可使用

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");
  });
}