Reputation: 334
I have a problem with connection to mongoose. I'm trying to connect to mongoDB atlas and getting MongoNetworkError.
That's my code and error log. Thank you for a help.
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser =require('body-parser');
const mongoose = require('mongoose');
const productRoutes = require('./api/routes/products');
const ordersRoutes = require('./api/routes/orders');
mongoose.connect('mongodb://robertRobot:[email protected]:27017,nodeshop-shard-00-01-5oqzt.mongodb.net:27017,nodeshop-shard-00-02-5oqzt.mongodb.net:27017/test?ssl=true&replicaSet=NodeShop-shard-0&authSource=admin&retryWrites=true',
{ useNewUrlParser: true }
).then().catch(err=>{
console.log('xxxxxxxxxxxxxxxxxxxxxx');
console.log(err);
});
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());
app.use((req,re,next)=>{
res.header('access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Autorisation');
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
next();
}
});
app.use('/products', productRoutes);
app.use('/orders', ordersRoutes);
app.use((req, res,next)=>{
const error = new Error('not found');
error.status = 404;
next(error);
});
app.use((error, req, res, next)=>{
res.status(error.status || 500);
res.json({
error: {
message : '500 error'
}
});
});
module.exports = app;
Error log:
{ MongoNetworkError: connection 4 to nodeshop-shard-00-02-5oqzt.mongodb.net:27017 closed
at TLSSocket.<anonymous> (/Users/robertas/Desktop/node-js/restApi/node_modules/mongodb-core/lib/connection/connection.js:276:9)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:121:20)
at TLSSocket.emit (events.js:211:7)
at _handle.close (net.js:561:12)
at TCP.done [as _onclose] (_tls_wrap.js:360:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Upvotes: 2
Views: 2875
Reputation: 224
Restart your MongoDB. If using Linux then try the command:
sudo service mongod start
Also, just give mongo in the mongo shell and check whether it's working.
Upvotes: 1
Reputation: 1
You need to enter IP 0.0.0.0/0 to Network Access in Atlas MongoDB. It means that everyone can connect to your DB
Upvotes: 0