除非我重新启动节点服务器,否则 mongodb 更新不会显示 [英] mongodb updates not showing unless I restart the node server

查看:61
本文介绍了除非我重新启动节点服务器,否则 mongodb 更新不会显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我更新 mongodb 数据时,它只显示我是否重新启动服务器(由更新文件触发).

我尝试了多种方法&发现其他人有类似的问题,但没有我能理解的答案.即 如何在更新 mongodb 时自动重启节点服务器我知道我不想重启服务器,但那是数据更新的时候.

const http = require('http');const MongoClient = require('mongodb').MongoClient;const 主机名 = '本地主机';常量端口 = 3000;让 dbResponse = '没什么';让 statsDB;//保存数据库连接//连接数据库MongoClient.connect("mongodb://adminMongo:XXXX@localhost:12345", function (err, db) {statsDB = db.db('stats');//数据库插入/更新/查询代码在这里..如果(!错误){statsDB.collection('stats').find().toArray(function(err, docs){dbResponse = 文档;//db.close();});}别的{dbResponse = 错误;}});const server = http.createServer((req, res) => {res.statusCode = 200;res.setHeader('Content-Type', 'application/json');//nodejs路由器让 url = require('url').parse(req.url, true);if(url.pathname ==='/mongo'){res.end(`${JSON.stringify(dbResponse)}\n`);//这有效}else if(url.pathname ==='/mongo/update'){dbUpdate(url.query.data_category, url.query.data_end);}别的{res.end(`${JSON.stringify(dbResponse)}\n`);//这有效}});server.listen(端口,主机名,()=> {console.log(`服务器运行在 http://${hostname}:${port}/`);});/* 数据库函数 *///尚未设置为路由...函数 dbInsert(dataCategory, dataTitle, dataStart, dataEnd, dataInterval){var doc = {data_category:dataCategory,数据标题:数据标题,数据开始:数据开始,数据结束:数据结束,数据间隔:数据间隔};//使用 insertOne 将文档插入到 'users' 集合statsDB.collection('stats').insertOne(doc, function(err, res) {如果(错误)抛出错误;console.log("插入的文档");//完成后关闭与 db 的连接});}函数 dbUpdate(dataCategory, dataEnd){MongoClient.connect("mongodb://adminMongo:XXXX@localhost:12345", function (err, db) {statsDB = db.db('stats');//dbResponse = JSON.stringify(statsDB);//如果(错误)抛出错误;//在这里写数据库插入/更新/查询代码..如果(!错误){//dbResponse.push({'params': dataEnd});statsDB.collection('stats').updateOne({数据类别:数据类别},{$set: {data_end: dataEnd}},{多:真})}别的{dbResponse = 错误;}});}//dbUpdate('games-won', '5');函数 dbDelete(dataCategory){statsDB.collection('stats').deleteOne({data_category: dataCategory});//statsDB.collection('stats').deleteMany({data_category: 'toenails-lost'});如果(错误)抛出错误;}

一旦更新,无需重启服务器即可更新数据.

解决方案

当服务器启动并且一切都通过该连接运行时,尝试使用一个连接到数据库的脚本.

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

<预><代码>const url = "mongodb://adminMongo:XXXX@localhost:12345";//概述 mongo db 连接的选项const mongoOptions = { useUnifiedTopology: true };//创建一个新的 mongo 客户端来连接数据库const client = new MongoClient(url, mongoOptions);//在服务器启动时连接到 mongodb 数据库客户端连接(功能(错误){如果(错误){console.log('无法连接到MongoDB数据库');//如果无法建立到数据库的连接,则退出进程process.exit(1);} 别的 {//创建本地主机服务器server.listen(端口,主机名,()=> {console.log(`服务器运行在 http://${hostname}:${port}/`);});}});

那么当你要查询数据库时你就不需要打开一个新的连接

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

function dbInsert(dataCategory, dataTitle, dataStart, dataEnd, dataInterval){var doc = {data_category:dataCategory,数据标题:数据标题,数据开始:数据开始,数据结束:数据结束,数据间隔:数据间隔};//使用 insertOne 将文档插入到 'users' 集合statsDB.collection('stats').insertOne(doc, function(err, res) {如果(错误)抛出错误;console.log(文档插入");});}

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.

解决方案

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

这篇关于除非我重新启动节点服务器,否则 mongodb 更新不会显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆