i could'nt connect to mongodb anymore? - javascript

in the first try i could connect to my mongodb account at it worked correctly but after 24h hours i couldnt connect anymore at it show me this problem :
>
npm run start
> devconnector#1.0.0 start C:\Users\DELL\Desktop\devconnector
> node server.js
Server running on port 5000
MongoTimeoutError: Server selection timed out after 30000 ms
at Timeout._onTimeout (C:\Users\DELL\Desktop\devconnector\node_modules\mongodb\lib\core\sdam\topology.js:897:9)
at listOnTimeout (internal/timers.js:531:17)
at processTimers (internal/timers.js:475:7) {
name: 'MongoTimeoutError',
reason: MongoNetworkError: connection 79 to cluster0-shard-00-00-15tsv.mongodb.net:27017
closed
at TLSSocket.<anonymous> (C:\Users\DELL\Desktop\devconnector\node_modules\mongodb\lib\core\connection\connection.js:356:9)
at Object.onceWrapper (events.js:300:26)
at TLSSocket.emit (events.js:210:5)
at net.js:659:12
at TCP.done (_tls_wrap.js:481:7) {
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
},
[Symbol(mongoErrorContextSymbol)]: {}
}
this is my keys.js file : module.exports = {
mongoURI : "mongodb+srv://jassem:<*******>#cluster0-15tsv.mongodb.net/test",
} ;
and this my code to connect to my Mongodb account :
//Connect To mongoDB
mongoose
const express = require ('express') ; const mongoose = require ('mongoose') ;
.connect(db, {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }) .then(()=> console.log('MongoDB connected')) .catch(err => console.log(err)) ;

Related

how to clear this mongoose error in terminal [duplicate]

I have a problem when I try to connect my app with my database with Mongoose. Already tried following solutions that I found on google:
restarting MongoDB service on windows
manually open db with cmd located on bin file of mongodb
But I can't solve it. Can anyone help me ?
//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
And throw's me , this error
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20)
at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
I try to put the port on my connection code like this
//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
and it throw's me another error
MongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864
at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20)
at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:3000' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
If the Error states:
connect() Error :MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
Then the connection to localhost is refused on the IPv6 address ::1 .
Mongoose per default uses IPv6 ..
For a quick check you can set the IPv4 address explicit:
mongoose.connect('mongodb://127.0.0.1/test')
Simply pass third parameter family:4 ie.
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
I finally solved it.
Enabling the IPV6 that MongoDB has disabled by default. Using the following command line on CMD:
mongod --ipv6
And then try again the connection and it works!
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
Posted on behalf of the question asker
const uri = 'mongodb://localhost:27017/test';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
autoIndex: false, // Don't build indexes
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
}
const connectWithDB = () => {
mongoose.connect(uri, options, (err, db) => {
if (err) console.error(err);
else console.log("database connection")
})
}
connectWithDB()
Probably the hostname/IP of the server to which you want to connect is not correctly set.
I'm used to see that error as:
MongooseServerSelectionError: connect ECONNREFUSED <hostname/hostIP>:<port>
and in the console log you've posted, the <hostname/hostIP> part is malformed/missing.
Example - for a mongodb server running locally on port 27017 this is the error when server is down:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
If you're using mongodb URI to connect to the db make sure that it looks like this
"mongodb://<hostname/hostIP>:<port>"
Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1
However, net.ipv6 defaults to false.
The best option would be to start the MongoDB with this configuration:
net:
ipv6: true
bindIpAll: true
or
net:
ipv6: true
bindIp: localhost
Then all variants should work:
C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
If you don't run MongoDB as a service then it would be
mongod --bind_ip_all --ipv6 <other options>
NB, I don't like configuration
net:
bindIp: <ip_address>
in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true
Open your terminal and type this command: mongod
Then use your app.js to establish a connection by writing this code :
const mongoose=require("mongoose");
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
It's done now. Simply open your mongo shell or your mongodb compass and look for whatever you have added.
I also faced the same problem those commands worked for me(Ubuntu machine)
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
Then
sudo service mongod restart

Issue connection to database

I have an application with a frontend that uses React and a backend that uses the Nodejs environment with the Express framework.
To communicate and store the data I use MongoDB.
I have been developing this application for a few weeks now and everything is working fine until today.
This morning again I developed and I could test everything, it responded well.
Since two hours when I write npm start in my terminal on vscode in the backend folder, I get an error while before my server was running fine. I want to specify that I made a 30min break between when I stopped coding this morning and when I started again this afternoon, I didn't change anything in the code in the meantime but the server doesn't start anymore. I also want to say that npm start in my frontend folder is still working fine.
Implementing mongo db in my backend code
db.js in models folder
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI, { useNewURLParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function () {
console.log('Connected')
});
implementation of mongo in app.js of backend folder
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var bodyParser = require("body-parser");
var logger = require("morgan");
var cors = require("cors");
require('dotenv').config();
var whitelist = ['http://localhost:3000']
var corsOption = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
var getAPIRouter = require("./routes/apiRoutes.js");
var app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(cors(corsOption));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
app.use("/", getAPIRouter);
require('./routes/auth.routes')(app);
require('./routes/user.routes')(app);
const db = require("./models");
const Role = db.role;
db.mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
//just for first time running
function initial() {
Role.estimatedDocumentCount((err, count) => {
if (!err && count === 0) {
new Role({
name: "user"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'user' to roles collection");
});
new Role({
name: "moderator"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'moderator' to roles collection");
});
new Role({
name: "admin"
}).save(err => {
if (err) {
console.log("error", err);
}
console.log("added 'admin' to roles collection");
});
}
});
}
app.use(function (req, res, next) {
next(createError(404));
});
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
My error in the terminal
PS C:\Users\deyga\Documents\GitHub\PPE\backendPPE> npm start
> backendppe#0.0.0 start C:\Users\deyga\Documents\GitHub\PPE\backendPPE
> node ./bin/www
Successfully connect to MongoDB.
connection error MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your
Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
at NativeConnection.Connection.openUri (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:340:10
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:1174:10)
at Mongoose.connect (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:339:20)
at Object.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\models\db.js:2:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.0ynbf.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-01.0ynbf.mongodb.net:27017' => [ServerDescription],
'cluster0-shard-00-02.0ynbf.mongodb.net:27017' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-sujybn-shard-0',
logicalSessionTimeoutMinutes: undefined
}
}
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're
trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
at NativeConnection.Connection.openUri (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:340:10
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:1174:10)
at Mongoose.connect (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongoose\lib\index.js:339:20)
at Object.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\models\db.js:2:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(3) {
'cluster0-shard-00-00.0ynbf.mongodb.net:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: 'cluster0-shard-00-00.0ynbf.mongodb.net',
port: 27017
},
address: 'cluster0-shard-00-00.0ynbf.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2826297,
lastWriteDate: 0,
error: MongoNetworkError: connect ETIMEDOUT 108.129.27.210:27017
at connectionFailureError (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:381:20)
at TLSSocket.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
},
'cluster0-shard-00-01.0ynbf.mongodb.net:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: 'cluster0-shard-00-01.0ynbf.mongodb.net',
port: 27017
},
address: 'cluster0-shard-00-01.0ynbf.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2826308,
lastWriteDate: 0,
error: MongoNetworkError: connect ETIMEDOUT 52.212.197.12:27017
at connectionFailureError (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:381:20)
at TLSSocket.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
},
'cluster0-shard-00-02.0ynbf.mongodb.net:27017' => ServerDescription {
_hostAddress: HostAddress {
isIPv6: false,
host: 'cluster0-shard-00-02.0ynbf.mongodb.net',
port: 27017
},
address: 'cluster0-shard-00-02.0ynbf.mongodb.net:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 2826318,
lastWriteDate: 0,
error: MongoNetworkError: connect ETIMEDOUT 34.246.79.174:27017
at connectionFailureError (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:381:20)
at TLSSocket.<anonymous> (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'atlas-sujybn-shard-0',
logicalSessionTimeoutMinutes: undefined
}
}
Node.js v17.7.2
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! backendppe#0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the backendppe#0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\deyga\AppData\Roaming\npm-cache\_logs\2022-04-04T13_57_51_440Z-debug.log
Complete log of this run
0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli 'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli 'start'
1 verbose cli ]
2 info using npm#6.14.15
3 info using node#v14.18.0
4 verbose run-script [ 'prestart', 'start', 'poststart' ]
5 info lifecycle backendppe#0.0.0~prestart: backendppe#0.0.0
6 info lifecycle backendppe#0.0.0~start: backendppe#0.0.0
7 verbose lifecycle backendppe#0.0.0~start: unsafe-perm in lifecycle true
8 verbose lifecycle backendppe#0.0.0~start: PATH: C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Python310\Scripts\;C:\Python310\;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\Git\cmd;C:\Program Files\nodejs\;C:\ProgramData\chocolatey\bin;C:\Program Files\Docker\Docker\resources\bin;C:\ProgramData\DockerDesktop\version-bin;C:\Android\android-sdk\platform-tools;C:\Windows\System32\;C:\Users\deyga\AppData\Local\Microsoft\WindowsApps;C:\Users\deyga\AppData\Local\GitHubDesktop\bin;C:\Users\deyga\AppData\Local\Microsoft\WindowsApps;C:\texlive\2020\bin\win32;C:\Users\deyga\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\deyga\AppData\Roaming\npm;C:\Program Files\heroku\bin;C:\Users\deyga\Documents\GitHub\PROJECT_WEB_OCRES;
9 verbose lifecycle backendppe#0.0.0~start: CWD: C:\Users\deyga\Documents\GitHub\PPE\backendPPE
10 silly lifecycle backendppe#0.0.0~start: Args: [ '/d /s /c', 'node ./bin/www' ]
11 silly lifecycle backendppe#0.0.0~start: Returned: code: 1 signal: null
12 info lifecycle backendppe#0.0.0~start: Failed to exec start script
13 verbose stack Error: backendppe#0.0.0 start: `node ./bin/www`
13 verbose stack Exit status 1
13 verbose stack at EventEmitter.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\index.js:332:16)
13 verbose stack at EventEmitter.emit (events.js:400:28)
13 verbose stack at ChildProcess.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack at ChildProcess.emit (events.js:400:28)
13 verbose stack at maybeClose (internal/child_process.js:1058:16)
13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:293:5)
14 verbose pkgid backendppe#0.0.0
15 verbose cwd C:\Users\deyga\Documents\GitHub\PPE\backendPPE
16 verbose Windows_NT 10.0.19043
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
18 verbose node v14.18.0
19 verbose npm v6.14.15
20 error code ELIFECYCLE
21 error errno 1
22 error backendppe#0.0.0 start: `node ./bin/www`
22 error Exit status 1
23 error Failed at the backendppe#0.0.0 start script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
Message returned in the backend site when I try to access its route: "http://localhost:5000/api/forums"
Not allowed by CORS
Error: Not allowed by CORS
at origin (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\app.js:21:16)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\cors\lib\index.js:219:13
at optionsCallback (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\cors\lib\index.js:199:9)
at corsMiddleware (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\cors\lib\index.js:204:7)
at Layer.handle [as handle_request] (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:323:13)
at C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:341:12)
at next (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\deyga\Documents\GitHub\PPE\backendPPE\node_modules\express\lib\middleware\init.js:40:5)
I use two different ports for my backend server (port 5000) and the frontend (port 3000).
I tried to delete node module in my backend folder and then redo an npm install but it didn't change anything. I also tried to upgrade my npm without result either. I also tried to recover my ip address on https://www.whatismyip.com/ to add it in network access in MongoDB but it did not solve my problem either.
MongoDB Network Access settings
I tried to put as much information as possible about the error but if you find any missing let me know and I will try to add it as soon as possible.
I found several people with the same problem as me on the forums but no solution worked for me, if you could help me it would save me :)

MongooseServerSelectionError: connect ECONNREFUSED ::1:27017

I have a problem when I try to connect my app with my database with Mongoose. Already tried following solutions that I found on google:
restarting MongoDB service on windows
manually open db with cmd located on bin file of mongodb
But I can't solve it. Can anyone help me ?
//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
And throw's me , this error
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20)
at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
I try to put the port on my connection code like this
//my connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
and it throw's me another error
MongooseServerSelectionError: Invalid message size: 1347703880, max allowed: 67108864
at NativeConnection.Connection.openUri (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\connection.js:797:32)
at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:330:10 at C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise ()
at promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:1151:10)
at Mongoose.connect (C:\Users\ivan\Desktop\NodeJS\notes-app\node_modules\mongoose\lib\index.js:329:20)
at Object. (C:\Users\ivan\Desktop\NodeJS\notes-app\src\db.js:3:10)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { 'localhost:3000' => [ServerDescription] },
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
If the Error states:
connect() Error :MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
Then the connection to localhost is refused on the IPv6 address ::1 .
Mongoose per default uses IPv6 ..
For a quick check you can set the IPv4 address explicit:
mongoose.connect('mongodb://127.0.0.1/test')
Simply pass third parameter family:4 ie.
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
I finally solved it.
Enabling the IPV6 that MongoDB has disabled by default. Using the following command line on CMD:
mongod --ipv6
And then try again the connection and it works!
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
Posted on behalf of the question asker
const uri = 'mongodb://localhost:27017/test';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
autoIndex: false, // Don't build indexes
maxPoolSize: 10, // Maintain up to 10 socket connections
serverSelectionTimeoutMS: 5000, // Keep trying to send operations for 5 seconds
socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
family: 4 // Use IPv4, skip trying IPv6
}
const connectWithDB = () => {
mongoose.connect(uri, options, (err, db) => {
if (err) console.error(err);
else console.log("database connection")
})
}
connectWithDB()
Probably the hostname/IP of the server to which you want to connect is not correctly set.
I'm used to see that error as:
MongooseServerSelectionError: connect ECONNREFUSED <hostname/hostIP>:<port>
and in the console log you've posted, the <hostname/hostIP> part is malformed/missing.
Example - for a mongodb server running locally on port 27017 this is the error when server is down:
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
If you're using mongodb URI to connect to the db make sure that it looks like this
"mongodb://<hostname/hostIP>:<port>"
Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1
However, net.ipv6 defaults to false.
The best option would be to start the MongoDB with this configuration:
net:
ipv6: true
bindIpAll: true
or
net:
ipv6: true
bindIp: localhost
Then all variants should work:
C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
If you don't run MongoDB as a service then it would be
mongod --bind_ip_all --ipv6 <other options>
NB, I don't like configuration
net:
bindIp: <ip_address>
in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true
Open your terminal and type this command: mongod
Then use your app.js to establish a connection by writing this code :
const mongoose=require("mongoose");
mongoose.connect('mongodb://localhost/notes-db-app',{
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
})
It's done now. Simply open your mongo shell or your mongodb compass and look for whatever you have added.
I also faced the same problem those commands worked for me(Ubuntu machine)
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock
Then
sudo service mongod restart

Mongoose throws error ECONNREFUSED on Apollo-Express server

I am sorry if this question is stupid or dumb, please just point me in the right direction, every bit of help is greatly appreciated.
I am currently building a Apollo-Server using express and mongoose. I got the server running with GraphQL, but after connecting it with mongoose, which looks like this:
const express = require("express");
const { ApolloServer, gql } = require("apollo-server-express");
const fs = require("fs");
const port = 4000;
const path = "/graphql";
const app = express();
const typeDefs = gql(fs.readFileSync("./schema.graphql", { encoding: "utf8" }));
const resolvers = require("./resolvers");
const mongo = require('./config');
const { User } = require('./models');
const server = new ApolloServer({
typeDefs,
resolvers,
});
server.applyMiddleware({ app, path });
app.listen(port, () => console.info(`Server started on port ${port}`));
with this as my config:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const url = 'mongodb://localhost:27017/graphql';
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
};
//mongoose.connect(url, options);
//mongoose.connection.once('open', () => console.log("Connected to mongoDB at ${url}"));
var connectWithRetry = function () {
return mongoose.connect(url, options, function (err) {
if (err) {
console.error(
"Failed to connect to mongo on startup - retrying in 5 sec\n\n",
err
);
setTimeout(connectWithRetry, 5000);
}
mongoose.connection.once("open", () =>
console.log(`Connected to mongo at ${Constants.mongodbUrl}`)
);
});
};
connectWithRetry();
This is supposed to work right?
But when i call npm start server.js i get the following error:
npm start server.js
> start
> node server.js "server.js"
Server started on port 4000
Failed to connect to mongo on startup - retrying in 5 sec MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at NativeConnection.Connection.openUri (/Users/myUsername/newServer/server/node_modules/mongoose/lib/connection.js:832:32)
at /Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:345:10
at promiseOrCallback (/Users/myUsername/newServer/server/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
at Mongoose._promiseOrCallback (/Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (/Users/myUsername/newServer/server/node_modules/mongoose/lib/index.js:344:20)
at connectWithRetry (/Users/myUsername/newServer/server/config.js:16:19)
at Object.<anonymous> (/Users/myUsername/newServer/server/config.js:30:1)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Module.require (node:internal/modules/cjs/loader:997:19)
at require (node:internal/modules/cjs/helpers:92:18)
at Object.<anonymous> (/Users/myUsername/newServer/server/server.js:14:15)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) {
reason: TopologyDescription {
type: 'Unknown',
setName: null,
maxSetVersion: null,
maxElectionId: null,
servers: Map(1) { 'localhost:27017' => [ServerDescription] },
stale: false,
compatible: true,
compatibilityError: null,
logicalSessionTimeoutMinutes: null,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
commonWireVersion: null
}
}
If you need my installed npm-packages:
graphql-node-server# /path/server
├── apollo-server#2.19.1
├── express#4.17.1
├── graphql#15.4.0
├── mongodb#3.6.3
├── mongoose#5.11.11
└── nodemon#2.0.7
You need to start the MongoDB service before running your code. If it is not running then it will be on a continuous loop trying to reconnect.
Also when it is connected the open event will not be triggered. You need to move it outside of your connection function so it should be like this.
var connectWithRetry = function () {
return mongoose.connect(url, options, function (err) {
if (err) {
console.error(
"Failed to connect to mongo on startup - retrying in 5 sec\n\n",
err
);
setTimeout(connectWithRetry, 5000);
}
});
};
mongoose.connection.once("open", () =>
console.log(`Connected to mongo at ${url}`)
);
connectWithRetry();
My mistake was, that i needed to start the mongoDB process manually. If you did not, start it an rerun it, for me that fixed the issue.
mongod --config /usr/local/etc/mongod.conf --fork

Why Can't I connect SQL Server to my node js

I'm using the 'mssql' npm package to connect my SQL server to my node JS.
I went through a few questions, but it wasn't solved anywhere.
My SQL Server login credentials are-
server type : Database Engine
Server name : DESKTOP-MPF88ST\KUSHAL
authentication : sql server authentication
login : username
password : password
and the database I wanna get is schoolDB
and my code goes something like this
const sql =require("mssql")
const config = {
login: 'username',
password:'password',
server: 'localhost',
database: "schoolDB",
options : {
enableArithAbort: true
},
port : 1433
}
sql.connect(config, (err) => {
if(err){
console.log(err);
}
else {
console.log("Connected")
}
I have my TCP/IP enabled and set up, SQL Server Browser enabled, but it still throws the error-
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.<anonymous> (E:\Kushals\server\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:422:26)
at Connection.emit (events.js:315:20)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ESOCKET'
}
}
How can I solve it ??
Try this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
login: 'username',
password:'password',
database: 'schoolDB',
server: 'DESKTOP-MPF88ST\KUSHAL',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//sample query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
Ensure that the TCP/IP protocol is Enabled as it is disabled by default.
Steps:
Go to Computer management
Under Service and Applications -> SQL Server Configuration Manager
-> SQL Server Network configuration -> click on "Protocols for MSSQLSERVER"
You will see TCP/IP section (to enable right click and enable it)

Categories