When you try to connect to a MongoDB through Node JS using Mongoose, then you may come across the connection error such as MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16) { name: ‘MongoNetworkError’ }]

First make sure that your MongoDB database is running at port number 27017, else go to  “C:\Program Files\MongoDB\Server\your-version\bin”, run command prompt from here and run mongod from the command prompt.

If that doesn’t solve the problem, then go to your Node JS application and check the url for connecting to the database

in the new Mongoose versions, the preferred url is like this “mongodb://localhost/database-name” (use your database name at database-name). If you are getting error with this url, you can replace localhost with which makes the url “mongodb://“.

If you are using an earlier version of Mongoose, you can try with this url “mongodb://localhost:27017/database-name