Why can't I connect mongodb using node js?

Viewed 123

I have started my mongodb server and the software can actually connect it.
Mongodb started image
Error Gif
My node js code is

mongoose.connect("mongodb://localhost:27017/chat", { useNewUrlParser: true }).catch(err => console.log(err));

and it give me the error

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connection 0 to localhost:27017 closed
    at Socket.<anonymous> (D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\connection.js:439:9)
    at Object.onceWrapper (events.js:422:26)
    at Socket.emit (events.js:315:20)
    at TCP.<anonymous> (net.js:673:12)]
    at Pool.<anonymous> (D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\topologies\server.js:438:11)
    at Pool.emit (events.js:315:20)
    at D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\pool.js:562:14
    at D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\pool.js:995:11
    at callback (D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\connect.js:75:5)
    at D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\connect.js:101:9
    at _callback (D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\connection.js:328:7)
    at Connection.errorHandler (D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\connection.js:343:7)
    at Object.onceWrapper (events.js:422:26)
    at Connection.emit (events.js:315:20)
    at Socket.<anonymous> (D:\Web开发\fake-chatroom\server\node_modules\mongodb\lib\core\connection\connection.js:437:12)
    at Object.onceWrapper (events.js:422:26)
    at Socket.emit (events.js:315:20)
    at TCP.<anonymous> (net.js:673:12)
1 Answers

From the image you posted, mongodb is listening on the default port, 27017. Your code is attempting to open a connection to port 28019 which is the cause of the error.

Use the default port number in your code:

mongoose.connect("mongodb://localhost:27017/chat", { useNewUrlParser: true }).catch(err => console.log(err));
Related