Mongoose does not connect to local database - node.js

Previously I tried to connect it by setting dbURI to the URI that mongo gives you upon clicking "connect application" and it did not work, later I tried to set up a local database with mongoDB, where i downloaded it, set it up and all the like. I created the data/db folder as well and i can open up an empty database upon typing the link in compass. Regardless of all of that, mongoose still doesn't allow me to connect to the database, giving me this error:
MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (D:\tests\node_modules\mongodb\lib\cmap\connection.js:467:30)
at MessageStream.emit (node:events:527:28)
at processIncomingData (D:\tests\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
at MessageStream._write (D:\tests\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at TLSSocket.ondata (node:internal/streams/readable:754:22)
at TLSSocket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}
Here's my code:
const express = require('express');
const mongoose = require('mongoose');
const CPD = require("./database/log");
// express
const app = express();
// database
const dbURI = 'mongodb://localhost:27017/local'
mongoose.connect(dbURI).then((res) => console.log("success")).catch((err) => console.log(err))
//serverstuff
app.get('/', (req, res) => {
res.send('Welcome!')
})
app.listen(3000);

try using '127.0.0.1' instead of 'localhost'
const dbURI = 'mongodb://127.0.0.1:27017/local'

Related

I am using mongoDB atlas and I am getting MongoServerError. When I am using without .env file every thing is fine but with env it is throwing error

PORT= <port>
DB_HOST= <host>
DB_URI= <uri>
DB_NAME= <db>
DB_USER= <user>
DB_PASS= <pass>
// app.js file
import express from 'express';
import mongoose from 'mongoose';
import fetch from "node-fetch";
import Project from './project.js';
import dotenv from "dotenv";
dotenv.config()
console.log(dotenv.parsed);
const app = express();
mongoose
.connect(process.env.DB_URI,{
dbName: 'process.env.DB_NAME',
user: 'process.env.DB_USER',
pass: 'process.env.DB_PASS',
})
.then((result) => {
console.log("Database connected successfuly!");
})
.catch((err) => {
console.error(err);
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/project', (req, res) => {
Project.find({}, (err, data) => {
res.json(data);
});
});
const port= process.env.PORT || 3000
app.listen(port, () => {
console.log('starting server at port' + port);
})
// Error encountered
undefined
(node:5659) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
starting server at port3000
MongoServerError: bad auth : Authentication failed.
at MessageStream.messageHandler (/home/varsha/Documents/projects/node_modules/mongodb/lib/cmap/connection.js:467:30)
Please help how to resolve this issue. Thanks in advance
at MessageStream.emit (node:events:390:28)
at processIncomingData (/home/varsha/Documents/projects/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
at MessageStream._write (/home/varsha/Documents/projects/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
at writeOrBuffer (node:internal/streams/writable:389:12)
at _write (node:internal/streams/writable:330:10)
at MessageStream.Writable.write (node:internal/streams/writable:334:10)
at TLSSocket.ondata (node:internal/streams/readable:754:22)
at TLSSocket.emit (node:events:390:28)
at addChunk (node:internal/streams/readable:315:12) {
ok: 0,
code: 8000,
codeName: 'AtlasError'
}
This is because you are passing the env var name as a literal string, not the backing value.
Meaning, if you change this part:
dbName: 'process.env.DB_NAME',
user: 'process.env.DB_USER',
pass: 'process.env.DB_PASS',
to this:
dbName: process.env.DB_NAME,
user: process.env.DB_USER,
pass: process.env.DB_PASS,
as well as a .env file that contains:
NOTE: PORT is optional since you either use the .env value or 3000 (eg. const port = process.env.PORT || 3000)
PORT=1234
DB_URI=mongo://your.uri
DB_NAME=yourdbnamegoeshere
DB_USER=dbuser
DB_PASS=dbpass
Also, if you are publishing this code to a public repo, make sure you use a .gitignore file with .env in it.

Unhandled rejection OrientDB.RequestError: User or password not valid for username: admin, database: 'demodb'

Hy guys,
I'm facing some trouble in connecting to an orientdb database.
Here is my app.js code
const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
const OrientJs = require('orientjs');
var server = OrientJs({
host: "localhost",
password: "root",
username: "root",
useToken: true
});
var db = server.use({
name: 'demodb',
username: 'admin',
password: 'root',
useToken: true
});
server.list()
.then(function (dbs) {
console.log( dbs.length + ': database/s on the server.');
});
db.select().from('ArchaeologicalSites').all()
.then(function (result) {
console.log(result);
});
app.set('view engine', 'pug')
router.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/views/index.html'));
});
The debugger shows this message even if I try to change the password or the username in the server.use() function.
the message from the debugger:
Debugger listening on ws://127.0.0.1:5858/
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
Running at Port 3000
Unhandled rejection OrientDB.RequestError: User or password not valid for username: admin, database: 'demodb'
DB name="demodb"
at child.Operation.parseError (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\protocol33\operation.js:905:13)
at child.Operation.consume (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\protocol33\operation.js:496:35)
at Connection.process (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\connection.js:459:17)
at Connection.handleSocketData (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\connection.js:331:20)
at Socket.emit (events.js:376:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at Socket.Readable.push (internal/streams/readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
at TCP.callbackTrampoline (internal/async_hooks.js:134:14)
1: database/s on the server.
So...it correctly connects with server.use(), in fact server.list() works fine.
But when itcomes to the query it shows that maybe the var "db" has something wrong...
When i change the app.js to this:
var db = server.use({
name: 'demodb',
username: 'root',
password: 'root',
useToken: true
});
the error shown is this:
Debugger listening on ws://127.0.0.1:5858/
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
Running at Port 3000
1: database/s on the server.
Unhandled rejection OrientDB.RequestError: Invalid authentication info for access to the database com.orientechnologies.orient.core.metadata.security.auth.OTokenAuthInfo#1798dbcf
DB name="demodb"
at child.Operation.parseError (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\protocol33\operation.js:905:13)
at child.Operation.consume (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\protocol33\operation.js:496:35)
at Connection.process (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\connection.js:459:17)
at Connection.handleSocketData (C:\Users\\source\repos\ExpressApp3\ExpressApp3\node_modules\orientjs\lib\transport\binary\connection.js:331:20)
at Socket.emit (events.js:376:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at Socket.Readable.push (internal/streams/readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
at TCP.callbackTrampoline (internal/async_hooks.js:134:14)
Ceers

trouble connecting to mongodb

I am following a tutorial and trying to connect to mongodb, i have two files
the first is server.js with the following codes
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
//body parser middleware
app.use(bodyParser.json());
//DB config
const db = require('./config/keys').mongoURI;
//connect to mongo
mongoose
.connect(db,{ useNewUrlParser: true })
.then(()=>console.log('Connected to mongodb...'))
.catch(err=>console.log(err));
const port = process.env.PORT || 5000;
app.listen(port,()=>console.log(`server connected on port ${port}`));
The second is the config file
module.exports = {
mongoURI:'mongodb+srv://denis:password#shoppingapp-wmnbw.mongodb.net/shopping?retryWrites=true&w=majority'
}
what I am trying to achieve is to show on the console connected to mongodb...
instead I am given this error message
server connected on port 5000
(node:35030) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [shoppingapp-shard-00-01-wmnbw.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to shoppingapp-shard-00-01-wmnbw.mongodb.net:27017 closed
at TLSSocket.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connection.js:372:9)
at Object.onceWrapper (events.js:417:26)
at TLSSocket.emit (events.js:310:20)
at net.js:672:12
at TCP.done (_tls_wrap.js:557:7)]
at Pool.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:310:20)
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/pool.js:561:14
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/pool.js:1008:9
at callback (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:97:5)
at /home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:124:7
at _callback (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:349:5)
at Connection.errorHandler (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connect.js:365:5)
at Object.onceWrapper (events.js:417:26)
at Connection.emit (events.js:310:20)
at TLSSocket.<anonymous> (/home/denis/Desktop/projects/MERN_SHOPPING_LIST/node_modules/mongodb/lib/core/connection/connection.js:370:12)
at Object.onceWrapper (events.js:417:26)
at TLSSocket.emit (events.js:310:20)
at net.js:672:12
at TCP.done (_tls_wrap.js:557:7)
I have tried to change the driver version but still get the errors, where am I going wrong?
It turns out I was not connecting with the right IP address.

Mongo db Atlas 3.6.5 authentication failed

I am pretty new to node.js,am trying to write data to a free online mongo db atlas using mongoose,however i keep getting Authentication failed despite editing mongo db settings to connect from anywhere and also using correct username and password for the db user.
Here is my app.js file where i connect to mongo db
app.js:
const express = require('express');
const morgan = require('morgan');
const bodyParser= require('body-parser');
const mongoose = require('mongoose');
const app = express();
const productRoutes= require('./api/routes/products');
const ordersRoutes= require('./api/routes/orders');
mongoose.connect('mongodb+srv://hilary:'+process.env.MONGO_ATLAS_PW+'#node-rest-dnqwa.mongodb.net/test?retryWrites=true').catch(err => console.log(err));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use((req,res,next) =>{
res.header("Access-Control-Allow-Origin","*");
res.header('Access-Control-Allow-Headers','Origin,X-Requested-With,Content-Type,Accept,Authorization');
if(req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods','PUT,POST,GET,DELETE,PATCH');
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: error.message
}
})
})
module.exports = app;
i get this error in my terminal:
{ MongoError: authentication fail
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\topologies\replset.js:1430:15
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:877:7
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:853:20
at finish (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:174:16)
at handleEnd (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:184:7)
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\auth\scram.js:289:15
at C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:544:18
at process._tickCallback (internal/process/next_tick.js:112:11)
name: 'MongoError',
message: 'authentication fail',
errors:
[ { name: 'node-rest-shard-00-00-dnqwa.mongodb.net:27017',
err: [MongoError] },
{ name: 'node-rest-shard-00-02-dnqwa.mongodb.net:27017',
err: [MongoError] } ] }
I am certain am using correct name and password so why cant it authenticate me,server runs on my localhost
EDIT
So i followed link to docs and now connect this way:
mongoose.connect('mongodb://hilary:'+process.env.MONGO_ATLAS_PW+'#localhost:27017/test').catch(err => console.log(err));
I then get this error in terminal:
{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\topologies\server.js:505:11)
at Pool.emit (events.js:180:13)
at Connection.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\pool.js:329:12)
at Object.onceWrapper (events.js:272:13)
at Connection.emit (events.js:180:13)
at Socket.<anonymous> (C:\Users\Hiary\Documents\rest-api\node_modules\mongodb-core\lib\connection\connection.js:245:50)
at Object.onceWrapper (events.js:272:13)
at Socket.emit (events.js:180:13)
at emitErrorNT (internal/streams/destroy.js:64:8)
at process._tickCallback (internal/process/next_tick.js:114:19)
name: 'MongoNetworkError',
message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
What worked was a slight variation from the mongoose docs,it was suggested on the Atlas server,for everyone who has Mongodb 3.4+ connect using the regular mongo db driver even when using mongoose, my connection string looks like:
mongoose.connect('mongodb+srv://hilary:<password>#node-rest-dnqwa.mongodb.net').catch(err => console.log(err));

trying to connect to mongodb Atlas using nodeJs

I am working on a small project(REST API) using nodeJs + MongoDB. I have been able to install MongoDB locally and connect to it using mongoose. However for some reason, when I try to connect using MongoDB Atlas it fails. It looks like it connects but then after 2 seconds, I get an error message saying sockets closed(see error below). I have no clue what is going on. I have whitelisted my IP, checked my login info to make sure I am using the correct password and indeed I am using because I am able to connect using MongoDB compass. Any help is greatly appreciated.
My current local ENV package versions are:
nodeJs:V9.7.1
mongoose:V6.1
=== MongoDb Atlas ===
mongodb:3.6
Below is the code that I am using to connect to the database:
var express = require('express'),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
user = require('./api/models/userModel'),
config = require('./api/config');
bodyParser = require('body-parser');
var authRoutes = require('./api/routes/authRoutes'),
userRoutes = require('./api/routes/userRoutes'),
reviewRoutes = require('./api/routes/reviewRoutes');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://user:myPass#cluster0-shard-00-00 zd6jq.mongodb.net/myDb');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//Swagger Info
var options = {
explorer : true
};
app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
//END Swagger Info
//REGISTER ROUTES
userRoutes(app);
authRoutes(app);
reviewRoutes(app);
app.listen(port);
console.log('iReview RESTful API server listenning on port: ' + port);
module.exports = app;
====ERROR MESSAGE ===
/Users/mdiez/node_test/node_modules/mongodb/lib/server.js:228
process.nextTick(function() { throw err; })
^
MongoError: server cluster0-shard-00-00-zd6jq.mongodb.net:27017 sockets closed
at Pool.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/topologies/server.js:325:47)
at Object.onceWrapper (events.js:219:13)
at Pool.emit (events.js:127:13)
at Connection.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/pool.js:101:12)
at Object.onceWrapper (events.js:219:13)
at Connection.emit (events.js:127:13)
at Socket.<anonymous> (/Users/mdiez/node_test/node_modules/mongodb-core/lib/connection/connection.js:142:12)
at Object.onceWrapper (events.js:219:13)
at Socket.emit (events.js:127:13)
at TCP._handle.close [as _onclose] (net.js:558:12)
var uri = 'mongodb://<usernamr>:<password>#<clustername>/<dbname>?ssl=true&replicaSet=<replica setname>&authSource=admin';
var db = mongoose.connect(uri).catch((error) => { console.log(error); });
Specify the replica set name, ssl true and authentication database. This is based on reference from Atlas documentation.
You can use this code to connect to Compass and Application. You just need to the following:
replace all the three primary and secondary shard from Cluster -> Overview
replace natours-app with your cluster name.
Compass:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?authSource=admin&replicaSet=natours-app1-shard-0&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true
Application:
mongodb://babar_bahadur:PASSWORD#natours-app-shard-00-00-ybksz.mongodb.net:27017,natours-app-shard-00-01-ybksz.mongodb.net:27017,natours-app-shard-00-02-ybksz.mongodb.net:27017/test?ssl=true&replicaSet=natours-app-shard-0&authSource=admin&retryWrites=true

Resources