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



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

尝试了许多方法,并发现了其他有类似问题的方法,但没有我能理解的答案。即更新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;
}

更新后,应更新数据,而无需重新启动服务器。

当服务器启动并且所有内容都脱离该连接时,尝试使用一个数据库连接的脚本。

因此,当应用侦听时,您只有一个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");
  });
}

最新更新