Unable to connect to mongodb databse using node.js - node.js

I am unable to connect to mongodb from node.js using mongoose as database driver. Also I am getting the following error.
Error:
Error in DB connection:{"ok":0,"code":18,"codeName":"AuthenticationFailed","name":"MongoError"}
I am explaining my code below.
const mongoose = require('mongoose');
const dbUser = process.env.USERNAME || 'admin';
const dbPass = process.env.PASSWORD || 'admin';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;
console.log('url', url);
const options = {
useNewUrlParser: true,
useCreateIndex: true,
connectTimeoutMS: 5000000,
poolSize: 10000,
useUnifiedTopology: true
};
/*
1- Connect to mongo server
*/
mongoose.connect(url, options, (err) => {
if(!err) {
console.log('Mongodb connection with mongoose successed');
} else {
console.log('Error in DB connection:' + JSON.stringify(err, undefined, true));
}
})
Here the database edqart-db is not actually present inside that particular mongo server. I need once one record will insert the db will created dynamically. If I have let dbName = 'admin'; then my node is connected to mongodb but for other db which is not created from beginning its showing error. I need once one record is going to insert then the db edqart-db will created. Here I just need the similar method like client.db(dbName) of require('mongodb').MongoClient for mongoose also.

I don't think its possible to authenticate on non existing db.
Here is what you should do if you want to enable auth on edqart-db.
Create a database edqart-db.
Create a user on that edqart-db. lets say username=edqartReadUser and password=edqartReasPassword.
Then your existing code should work below url.
const dbUser = process.env.USERNAME || 'edqartReadUser';
const dbPass = process.env.PASSWORD || 'edqartReasPassword';
const dbServer = 'edqart-mongodb';
const dbPort = process.env.MONGO_PORT || '27017';
let dbName = 'edqart-db';
const url = `mongodb://${dbUser}:${dbPass}#${dbServer}:${dbPort}/${dbName}`;

Related

MongoAtlas Error: invalid schema, expected mongodb

I am trying to connect to MongoAtlas, however I keep getting
Error: invalid schema, expected mongodb
It seems to be that I can connect, but it cannot get my db from MongoAtlas. My try catch error returns me (node:5964) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined
.env
PORT = 9055
MONGO_URI =mongodb+srv://<my-db-username>:<my-password>#cluster0.vossd.mongodb.net/<db-name>?
retryWrites=true&w=majority
server.js
require('dotenv').config();
const port = Number.parseInt(process.env.PORT, 10);
const mongoUri = process.env.MONGO_URI;
const {MongoClient} = require('mongodb');
const express = require('express');
const Application = require('./application');
const application = Application();
const Health = require('./health');
const Product = require('./product');
const Cart = require('./cart');
const Order = require('./order');
async function main() {
let db;
try {
db = await MongoClient.connect(mongoUri);
console.log(db)
} catch (err) {
console.log(err);
}
application.use('/health', Health());
application.use('/product', Product(db));
application.use('/cart', Cart(db));
application.use('/order', Order(db));
const server = application.listen(port, () => {
const host = server.address().address;
const port = server.address().port;
console.log(`Shopping website server up and running, listening at http://${host}:${port}`);
});
}
main();
Everything works fine when I'm connected to my local db, so I'm unsure as to what I'm doing incorrectly. Any advice is much appreciated. Thank you!
This cannot read property 'collection' of undefined might be misleading as you have caught the error happening on connection. Hence db is null so if you access collection it will give this error. Below is the sample code from Mongo Atlas.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>#test.w7hgn.mongodb.net/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true }); // <-- note the option
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});

Connecting a node api to a cosmosdb

I'm am trying to connect my react app with a node api to my cosmos db. I'm able to get the server running but when I send a post or get request I don't get a response. I've updated the firewall to allow my ip and I've read just about every article I can find on connecting to cosmos, but none of the resources have helped.
Here is the connection code
const mongoose = require('mongoose');
const env = require('./env/environment');
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);
mongoose.Promise = global.Promise;
const mongoUri = `mongodb://${env.dbName}:${env.key}#${env.dbName}.mongo.cosmos.azure.com:${env.cosmosPort}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#${env.dbName}#`;
function connect() {
return mongoose.connect(mongoUri, { auth: { user: env.dbName, password: env.key }});
}
module.exports = {
connect,
mongoose
};
and then the env file looks like this
const cosmosPort = 1234; // replace with your port
const dbName = 'your-cosmos-db-name-goes-here';
const key = 'your-key-goes-here';
module.exports = {
cosmosPort,
dbName,
key
};
The env file has the actual information this is just an example.
Are you sure .env file can use const to define params? I'm not sure that. But I follow the offical document, I can connnect cosmosdb successfully.
It is recommended to refer to my screenshot, create a .env file, and replace your parameters to try.
var mongoose = require('mongoose');
var env = require('dotenv').config();
mongoose.connect("mongodb://"+process.env.COSMOSDB_HOST+":"+process.env.COSMOSDB_PORT+"/"+process.env.COSMOSDB_DBNAME+"?ssl=true&replicaSet=globaldb", {
auth: {
user: process.env.COSMODDB_USER,
password: process.env.COSMOSDB_PASSWORD
},
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: false
})
.then(() => console.log('Connection to CosmosDB successful'))
.catch((err) => console.error(err));
I think your mongoUri need to be in this format mongodb://${env.dbName}:${env.key}#${env.dbName}.mongo.cosmos.azure.com:${env.cosmosPort}/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#${env.dbName}#
Took some digging for me, and the documentation isn't great.

Not Able to Connect to Password-protected MongoDB Server/DB

After successfully testing my Node app against a local mongoDB db, I am now trying to connect to our server db - which, unlike my local mongoDB, is user and password protected.
I am running into issues while trying the connection to the server. Specifically, I am getting this error:
MongoError: MongoClient must be connected before calling
MongoClient.prototype.db
The creds I'm trying look something like this:
{
"MONGO_URL": "mongodb://myuser:mypassword#someurl.com:27017?authSource=admin",
"MONGO_DATABASE": "bta",
"MONGO_COLLECTION": "jobs"
}
And here is my connection code:
const config = require('./configuration');
const url = config.get('MONGO_URL');
const dbName = config.get('MONGO_DATABASE');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient(url);
async function getJobDetails() {
client.connect(async function () {
try {
const db = await client.db(dbName);
// do stuff
});
} catch (error) {
console.log(error);
}
});
}
What am I missing here?
I figured out what the issue was and was able to get it to connect. The issue was that the site is secure, so I had to add ssl=true to the url connection string:
const url = 'mongodb://user:password#someurl.com:27017/bta?ssl=true&authSource=admin';
try:
const mongoClient = require('mongodb').MongoClient;
mongoClient.connect(url, { useNewUrlParser: true }, function(client_err, client) {
if (client != null) {
var client_db = client.db(dbName);
}
client.close();
});
As MongoDB.
https://mongodb.github.io/node-mongodb-native/3.2/tutorials/connect/
And please Try double checking DB on the server if it has the right config.
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL with password example
const url = 'mongodb://user:password#address:27017?readPreference=primary&authSource=admin';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
This works for both valid localhost/server url

My web application stops running when connected to mongodb atlas

In local mongodb is running when i connect to mongodb atlas it is not connecting and there is no errors.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://NaveenS:naveen#frozenexpression-
jiptd.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, {useNewUrlParser: true,
useUnifiedTopology: true} );
client.connect(err => {
const collection = client.db("yelp_camp").collection("campgrounds");
client.close();
});
In uri your database name is test and you trying to connect 'yelp_camp' so write both same and try again.

node.js mongo db write concern

I am running node.js 10.22, windows 8 and mongodb not sure what version, but I just downloaded it today, when I run my code I am getting a message, please ensure you set the default write concern, I am trying to follow a YouTube video, and there is mention of this, and I am finding little about it on the internet, from what i found, when I set the db i should set j:true, or safe : true/false, but neither not working for me. I do get the console log that I'm connected and the host and port, but then I get the write concern message and can't type or do anything.
var mongo = require('mongodb');
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodeintro", new mongo.Server(host,port,{Fsync: true}));
db.open(function(error){
console.log("we are connected"+host + port);
})
Tried this all type of ways as well, still no luck, best i did was get back to the db write concern message, but was not able to even connect this time. What I'm really looking for is to be able to insert anything in mongo db, and i can figure out the rest.
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;
var host = "127.0.0.1";
var port = mongo.DEFAULT_PORT;
ArticleProvider = function(host, port) {
this.db= new Db('node-mongo-blog', new Server(host, port, {auto_reconnect: true}, {}));
this.db.open(function(error){
if(error){
console.log(error)
}
else{
console.log(port,host)
}
});
};
ArticleProvider(host,port)
When using mongodb-native directly, you should now use MongoClient.connect to open a database connection pool. It will set a default write concern for you.
var mongodb = require('mongodb');
mongodb.MongoClient.connect('mongodb://localhost/nodeintro', function(err, db) {
// db is your open nodeintro database connection pool here
});
MongoClient was a somewhat recent addition so the tutorial you're working from likely pre-dates it.
If you use {w:1} parameter in your insert or update operation, you might give this error. To overcome you can use {journal:true} parameter in your db settings.
For instance;
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON;
var db = new Db('Your DB Name', new Server('192.168.170.128', 27017), { journal : true });
db.open(function(err, db) {
var collection = db.collection('user');
collection.findOne({'_id':req.session.User._id}, function(err, user){
// some codes what do you want
collection.save( user, {w: 1}, function(err, user_id) {
// just close the db connection
db.close();
});
});
});

Resources