[Error: failed to connect to [localhost:27017]] from NodeJS to mongodb

后端 未结 6 875
不知归路
不知归路 2021-01-01 18:11

I am having problem connecting to MongoDB from NodeJS using following sample code. I tried running \"mongod\" with or without sudo but nodejs code still fail to connect. I a

相关标签:
6条回答
  • 2021-01-01 18:36

    The first time, I made the obvious mistake that mongod (the mongo Server) was not even running.

    The second time, I had both the Server (mongod) and the Client (mongo) running on my Windows; in separate Command Prompts (of course mongo running first). mongod and/or its Command Prompt was "hung up" (i.e. the last line only said this, and the last line remained like this despite attempts to connections:)

    2017-06-20T12:31:02.937-0600 I NETWORK  [thread1] waiting for connections on port 27017
    

    I clicked in the Command Prompt pressed the space-bar to "kick it" , and the Command Prompt printed lines like these:

    2017-06-20T12:31:48.517-0600 I NETWORK  [thread1] connection accepted from 127.0.0.1:50260 #1 (1 connection now open)
    

    Which worked!

    0 讨论(0)
  • 2021-01-01 18:39
    • This issue can occur if your mongoDBwasnot shutdown properly Mongodb can't connect to localhost but can connect to localhost's IP address
    • Start your mongoDB Server using follwoingcommand and then try same ./mongod --bind_ip localhost
    0 讨论(0)
  • 2021-01-01 18:44

    yes , I came across this error too, and my hosts is as follow: 127.0.0.1 xxxxxx(the ip of my computer) and when I ran npm start in express project, it got an error like that . After I tried to change the mapping of 127.0.0.1 to localhost, it had no error.

    0 讨论(0)
  • 2021-01-01 18:46

    Try adding 127.0.0.1 localhost in /private/etc/hosts file.

    0 讨论(0)
  • 2021-01-01 18:49

    Somebody on Github found a solution: Instead of writing:

    Mongoose.connect(config.database.url);
    

    Write:

    Mongoose.connect(config.database.url, {
      keepAlive: true,
      reconnectTries: Number.MAX_VALUE,
      useMongoClient: true
    });
    

    (Source https://github.com/Automattic/mongoose/issues/5399)

    0 讨论(0)
  • 2021-01-01 18:51

    Never mind, I was able to resolve the issue by using 127.0.0.1 instead of localhost, not sure why I have to use ip address. My tomcat, apache, redis, and even node server all works using localhost but not the mongodb. Is there is config I need change to make it work using local host?

    0 讨论(0)
提交回复
热议问题