I am creating a simple server using nodejs, expressJs and mongodb
here is server.js
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const db = require('./config/db');
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err)
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
Note: database info are all okay,
when i run node server.js , i get the following error :
C:\Users\Bonge\Documents\Projects\movies_database>node server.js
{ MongoError: Authentication failed.
at Function.MongoError.create (C:\Users\Bonge\Documents\Projects\movies_database\node_modules\mongodb-core\lib\error.js:31:11)
at C:\Users\Bonge\Documents\Projects\movies_database\node_modules\mongodb-core\lib\connection\pool.js:497:72
at authenticateStragglers (C:\Users\Bonge\Documents\Projects\movies_database\node_modules\mongodb-core\lib\connection\pool.js:443:16)
at Connection.messageHandler (C:\Users\Bonge\Documents\Projects\movies_database\node_modules\mongodb-core\lib\connection\pool.js:477:5)
at Socket.<anonymous> (C:\Users\Bonge\Documents\Projects\movies_database\node_modules\mongodb-core\lib\connection\connection.js:331:22)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at Socket.Readable.push (_stream_readable.js:208:10)
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
what is wrong with my code?
i found solution just created new database and new user and everything okay now
Related
//in my .env file
MOVIEREVIEWS_DB_URI=mongodb+srv://driiisdev:password123#cluster1.ektx7.mongodb.net/sample_mflix?retryWrites=true&w=majority
PORT=8000 //starting port of server
//in my index.js file
import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"
dotenv.config();
const uri = process.env.MOVIEREVIEWS_DB_URI;
const client = new mongodb.MongoClient(uri);
const port = process.env.PORT||5000;
(async ()=>{
try{
//Connect to the MongoDB cluster
await client.connect();
app.listen(port, ()=>{
console.log("server is running on port:" +port);
})
}catch(e){
console.error(e);
process.exit(1)
}
})().catch(console.error);
//in my server.js file
import express from 'express'
import cors from 'cors'
import movies from './api/movies.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/movies", movies)
app.use('*', (req,res)=>{
res.status(404).json({error:"not found"})
})
export default app
// on running nodemon server , the error i get:
Error: listen EACCES: permission denied 8000 //starting port of server
at Server.setupListenHandle [as _listen2] (node:net:1317:21)
at listenInCluster (node:net:1382:12)
at Server.listen (node:net:1480:5)
at Function.listen (C:\xampp\htdocs\driiisdev\movie-reviews\backend\node_modules\express\lib\application.js:635:24)
at main (file:///C:/xampp/htdocs/driiisdev/movie-reviews/backend/index.js:19:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1361:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '8000 //starting port of server',
port: -1
}
Trying to connect to the mongodb free database on mongodb-atlas
I've almost tried everything Checked the docs, Changed the url, Changing password and even deleted the user and created the new one but still not resolve the problem
here is myurl.js file
module.exports = {
mongoURL: "mongodb+srv://nansDB:nansDB123#nodecluster-qs6cv.mongodb.net/test?retryWrites=true&w=majority",
secret: "mystrongsecret"
}
here is my index.js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
//mongodb Configuration
const db = require('./setup/myurl').mongoURL;
//attempt to connect to database
mongoose.connect(db, { useNewUrlParser: true })
.then(()=> console.log('MongoDb Connect successfully'))
.catch(err => console.log(err));
const port = process.env.PORT || 3000;
here are the error lines I'm getting whenever I tried to run
{ MongoNetworkError: failed to connect to server [nodecluster-shard-00-02-qs6cv.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to nodecluster-shard-00-02-qs6cv.mongodb.net:27017 closed]
at Pool.<anonymous> (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\topologies\server.js:431:11)
at Pool.emit (events.js:189:13)
at connect (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\pool.js:557:14)
at callback (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connect.js:109:5)
at runCommand (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connect.js:129:7)
at Connection.errorHandler (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connect.js:321:5)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at TLSSocket.<anonymous> (D:\nodejsProject\bigStack\node_modules\mongodb-core\lib\connection\connection.js:350:12)
at Object.onceWrapper (events.js:277:13)
at TLSSocket.emit (events.js:189:13)
at _handle.close (net.js:597:12)
at TCP.done (_tls_wrap.js:388:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Its solved actually my whitelisted ip was changed because of connection issue [reconnecting to wifi]. Although my suggestion is checked whether the ip you whitelisted is exists or not.
I tried to connect MongoDB through mLab.com. It got redirected to MongoDB Atlas. I created one project and cluster. When trying to connect I get the Bad Authentication error, though my credentials are correct.
Password holds special characters. I tried replacing those special characters with ASCII hex code as well, but no response.
I replace my password in the below code
config/keys.js
module.exports = {
mongoURI: `mongodb+srv://Nikhilesh:<password>#devconnector-gicbg.mongodb.net/test?retryWrites=true`
};
server.js
const mongoose = require("mongoose");
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("DB Connected"))
.catch(e => console.log(e));
Result:
{ MongoError: bad auth Authentication failed.
at _authenticateSingleConnection (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\auth\auth_provider.js:46:25)
at sendAuthCommand (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\auth\scram.js:214:18)
at Connection.messageHandler (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\connection\connect.js:334:5)
at Connection.emit (events.js:182:13)
at processMessage (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\connection\connection.js:364:10)
at TLSSocket.<anonymous> (F:\Web Development\MERN\Projects\DevConnector\node_modules\mongodb-core\lib\connection\connection.js:533:15)
at TLSSocket.emit (events.js:182:13)
at addChunk (_stream_readable.js:283:12)
at readableAddChunk (_stream_readable.js:264:11)
at TLSSocket.Readable.push (_stream_readable.js:219:10)
at TLSWrap.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
ok: 0,
errmsg: 'bad auth Authentication failed.',
code: 8000,
codeName: 'AtlasError',
name: 'MongoError',
[Symbol(mongoErrorContextSymbol)]: {} }
Downgrade your mongoose to 5.4.6.
Below mongoose connect set of codes, add
mongoose.Promise = global.Promise;
Let me know if it works.
I'm trying to create a simple rest API with a mongodb.
I have a server.js file
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-Parser');
const app = express();
app.use(bodyParser.json());
const db = require('./config/keys').mongoURI;
mongoose
.connect('mongodb://test:test123#ds241012.mlab.com:41012/mern_shopping')
.then(() => console.log('DB Connected'))
.catch(err => console.log(err));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log('Server started'));
I'm using nodemon
When I run npm run server I get the following error
(node:65209) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
then I got error in console
failed to connect to server
How do I fix this
Update
With {useNewUrlParser: true} the server starts but if I touch the server.js file I get this.
Server started
{ MongoNetworkError: failed to connect to server [ds241012.mlab.com:41012] on first connect [MongoNetworkError: connection 0 to ds241012.mlab.com:41012 timed out]
at Pool.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/topologies/server.js:564:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/connection/pool.js:317:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (/Users/test/Documents/_Work/cd/React/mern-shopping-list/node_modules/mongodb-core/lib/connection/connection.js:257:10)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:420:8)
at ontimeout (timers.js:482:11)
at tryOnTimeout (timers.js:317:5)
at Timer.listOnTimeout (timers.js:277:5)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Here is the error message which i got while trying to run the project using gulp. I guess the problem is caused because of mongodb.
Gulp is running my app on PORT: 8000
events.js:160
throw er; // Unhandled 'error' event
^
MongoError: failed to connect to server [localhost:27017] on first connect
[MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\H SHASHANK
KUMAR\Desktop\code\node_modules\mongodb-core\lib\topologies\server.js:336:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (C:\Users\H SHASHANK KUMAR\Desktop\code\node_modules\mongodb-core\lib\connection\pool.js:280:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (C:\Users\H SHASHANK
KUMAR\Desktop\code\node_modules\mongodb-
core\lib\connection\connection.js:187:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1277:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Below is the code which may contain the error.
var express = require('express')
mongoose = require('mongoose'); // creating reference for express
var db = mongoose.connect('mongodb://localhost/bookAPI'); //using mongoose
to connect to mongo db.
var Book = require('./models/bookModel'); //mongo db uees models to retrive
data.
var app = express(); // creating an instance of express to run app.
var port = process.env.PORT || 3000;
var bookRouter = express.Router();
bookRouter.route('/Books')
.get(function(req, res){
Book.find(function(err, books){
if(err)
console.log(err);
else
res.json(books);
});
});
app.use('/api', bookRouter);
app.get('/', function(req, res){
res.send('welcome to my API');
});
app.listen(port, function(){
console.log('Gulp is running my app on PORT: '+port);
});
I have tried searching for the error in other possible post on stack overflow but i didn't find any fix for my problem.