简体   繁体   English

通过Node.js启动MongoDB,然后进行连接

[英]Starting up MongoDB through Node.js and then connecting

I'd like to start the MongoDB through Node.js to save myself the trouble of having to do it manually each time, however I'm uncertain what the best method to use is, or for that matter, how to incorporate it, and therefore the dilemma. 我想通过Node.js启动MongoDB,以免于每次都必须手动进行操作的麻烦,但是我不确定使用的最佳方法是什么,或者如何合并它,以及因此陷入困境。

I believe the reason that this code is not working (ECONNREFUSED) is that the mongod.exe is not given enough time to start up. 我相信此代码无法正常工作(ECONNREFUSED)的原因是mongod.exe没有足够的时间启动。 If true, what would be the best method to around this? 如果为真,那么解决此问题的最佳方法是什么? Some sort of loop? 某种循环? Checking the status of the DB somehow? 以某种方式检查数据库的状态? Some sort of synchronous timer? 某种同步计时器?

Ideally, the server should check first if the MongoDB is already running before attempting to start it up, and if it fails to start up and connect after so many attempts to do something else. 理想情况下,服务器应先尝试检查MongoDB是否已在运行,然后再尝试启动它,以及经过多次尝试执行其他操作后它是否无法启动并连接。 This sounds like a good plan to me but unforunately I do not know where to start. 这听起来对我来说是个好计划,但不幸的是我不知道从哪里开始。

I'm really new to coding, and I'm perhaps a little too ambitious with my goals... if I'm doing anything wrong, please kindly let me know. 我对编码真的很陌生,也许我对自己的目标有些野心勃勃……如果我做错了什么,请告诉我。

const express = require('express');
const bodyParser= require('body-parser');
const app = express();
const MongoClient = require('mongodb').MongoClient
const execFile = require('child_process').execFile;

app.use(bodyParser.urlencoded({extended: true}))

var db

execFile("C:/Program Files/MongoDB/Server/3.2/bin/mongod.exe", ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);

});

MongoClient.connect('mongodb://localhost:27017/db', (err, database) => {
  if (err) return console.log(err)
  db = database
  app.listen(3000, function() {
  console.log('listening on 3000')
  })
})

You could wait till mongodb will start, then connect. 您可以等到mongodb将启动,然后再连接。 Here is the example 这是例子

  execFile("C:/Program Files/MongoDB/Server/3.2/bin/mongod.exe",  ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);

  MongoClient.connect('mongodb://localhost:27017/db', (err, database) => {

   if (err) return console.log(err)
   db = database
   app.listen(3000, function() {
     console.log('listening on 3000')
    })
  })

 });

Also in your example you start mongod with --version parameter, and presumably your intention is to start the db itself, correct? 同样在您的示例中,您使用--version参数启动mongod,并且大概是要启动数据库本身,对吗? So just drop --version parameter. 因此,只需删除--version参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM