MongoDb, how to get database from Client object when its name specified in URI? - node.js

When I initiate my Express app, I define all required parameters in Environmental Variables.
According to code here:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});
To get a database object I need:
To pass database name when I initialize my application. One more environment variable, don't like it.
To parse URI object like this: mongodb://localhost:27017/myproject to extract database name. One more line of code, don't like it either.
Is there another 3rd solution? When I tried to debug client object which returned if connection was successful I've seen that it already contains name of the database connected to see screenshot below, but I haven't found any official API how to use it. Use a "hacky" way I don't like too.

This is now simply done by simply not passing any variable to client.db().
As documentation states out:
The name of the database we want to use. If not provided, use database
name from connection string.
http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#db

Related

Database Connection using common module is not working [ mongoose and mongodb ]

I am trying to implement a common module for MongoDB connection using mongoose. and want to use the connection in other application for database operation. but facing issue when trying to use common database module. operation is halted / hanging after creating db connection. here is my codebase.
When I am using module specific dababase connection, then it is working fine, but when I am using common database connection it is hanging
Common DB Module
'use strict'
const mongoose = require('mongoose');
const DBOptions = require('./DBOption');
require("dotenv").config();
mongoose.Promise = global.Promise;
let isConnected;
const connectToDatabase = (MONGODB_URL) => {
if (isConnected) {
console.log('using existing database connection');
return Promise.resolve();
}
console.log('using new database connection');
console.log('DBOptions >> '+JSON.stringify(DBOptions));
return mongoose.connect(MONGODB_URL, DBOptions)
.then(db => {
console.log('db.connections[0].readyState >> '+db.connections[0].readyState);
isConnected = db.connections[0].readyState;
});
};
module.exports = connectToDatabase;
API Controller
const dbConnection = require('../DB/connection') // Internal Class
const DBConnection = require('as-common-util').connectToDatabase; // Common Class
/**
*
*/
app.get('/usr/alluser', async (req, res) => {
try {
//await dbConnection(process.env.MONGODB_URL) // This is working
await DBConnection(process.env.MONGODB_URL) // Code is hanging for this
let allUsers = await UserService.getAllUser()
console.log("All Users >> " + allUsers)
if (allUsers) {
return res.status(200).send(
new APIResponse({
success: true,
obj: allUsers
})
)
}
} catch (error) {
console.log(error)
}
})
It is hanging at following position
using new database connection
DBOptions >>
{"useNewUrlParser":true,"useUnifiedTopology":true,"useCreateIndex":true,"useFindAndModify":false,"autoIndex":false,"poolSize":10,"serverSelectionTimeoutMS":5000,"socketTimeoutMS":45000,"family":4}
db.connections[0].readyState >> 1
I am confused why same code is not working for common module.
This kind of pattern is not how Mongoose is meant to be used. Under the hood, Mongoose passes the underlying connection to the models in your module without the user really knowing anything about what is going on. That's why you can do magic stuff like MyModel.find() without ever having to create a model object yourself, or pass a db connection object to it.
If your db connection is in another module though, Mongoose won't be able to make those connections between your models and the MongoDB client connection since the models are no longer being registered on the mongoose object that is actually connected, and as a result, any requests you make using your models will break, since they will always be trying to connect through the object in your module.
There are other reasons why this won't, and shouldn't, work though. You're not supposed to be able to split a client. Doing so would make it unclear where communication along a client is coming from, or going to. You could change your function to make it return an established client connection. But your Mongoose models still wouldn't work. You would just be left with raw mongodb. If you want to do that, you might as well just uninstall Mongoose and use the mongodb library. Ultimately, you don't really gain anything from initializing the connection in a shared module. Initializing a connection is just a couple lines of code.
I doubt it's the connection that you want to share, rather it's the models (I'm guessing). You can put those in a shared module, and export them as a kind of connector function that injects the a given Mongoose instance into the models. See: Defining Mongoose Models in Separate Module.

MongoError - Authentication error (password with #)

Here is my code in my NodeJS application, to connect to my MongoDB engine :
const collection = 'mynewcollection';
const password = 'passwordwithan#';
const mongoUrl = `mongodb://admin:${encodeURIComponent(password)}#mymongobase.net/${collection}`;
// Connect using the connection string
MongoClient.connect(mongoUrl, {useNewUrlParser: true}, function(err, db) {
console.log(err.toString())
});
I get an authentication error. I tried several things to handle the '#' character and reading the documentation I thought that it was the good one...
But it is still failing even if the user and password are the good one.
Is the API correctly used ? Do you understand what is wrong ?
Thanks in advance.
OK I found the solution.
If you use :
const mongoUrl = `mongodb://admin:${encodeURIComponent(password)}#mymongobase.net/${collection}`;
Mongo will try to connect with admin/password defined on the collection.
If you don't put the collection in the mongo url :
const mongoUrl = `mongodb://admin:${encodeURIComponent(password)}#mymongobase.net`;
Then you can use the super user defined on all the mongo engine.

More than one Mongo endpoint in same API

My NodeJS application has form with text input field (for search) and a dropdown mongo for DEV, UAT and Production database options.
Based on the user selection respective database has to be accessed.
I want to know how to dynamically handle /change different database endpoint or change node env in run-time ?
One way that comes to my mind is to disconnect and connect again. If you are using mongoose, do something like:
var mongoose = require('mongoose')
...
try {
mongoose.disconnect();
mongoose.connect(mongoURL);
catch (e) {
console.log(e);
}
every time and take the mongoURL from the user input.
Another way is to use multiple connections:
var mongoose = require('mongoose')
var conn = mongoose.createConnection('mongodb://localhost/db1');
var conn2 = mongoose.createConnection('mongodb://localhost/db2');
and then choose the connection that you want to use depending on the user choice. I prefer this last one.
Take a look at this answer for more info:
https://stackoverflow.com/a/32909008/7041393

Create Bookshelf.js models without connection and make connection in route files

I have Bookshelf.js models (a general model with parse() and format() functions and a model for each table that extends the general model) and routes that use these models. The database is PostgreSQL. But I have users in a SQLite database and each user has its own PostgreSQL connection options. I can retrieve the current user and expose its database connection options in the request, so every route knows how to connect to PostgreSQL. But how can I connect and use my Bookshelf.js models in a route? This is an example of what I am trying to do in a routes file:
var express = require('express'),
knex = require('knex'),
// This should be the file that exposes all models.
// Every model exposed, extends the general model.
// But it already requires a connection when init Bookshelf.js...
dataBookshelf = require('../models'),
router = express.Router();
router.get('/items/:id',function(req,res,next) {
// In req.db I have PostgreSQL connection options for the current user.
var connection = req.db;
// Make a connection to PostgreSQL.
var db = dataBookshelf(knex(connection));
// Use Items model.
var Items = db.Items;
Items.read(req.params.id).then(function(item) {
res.json(item);
}).catch(Items.NotFoundError,function() {
var err = new Error('Item not found.');
res.status(400).json(err);
});
});
module.exports = router;
If there is another way to save the current user connection options globally and to use them in the module that exposes Bookshelf.js instance, instead of passing them in the request, it should be better and safer.

Create a connection to the mongodb if connection is not established

I am new to node.js and mongoose.
I am trying to check whether a database with supplied name exists or not,
if exists,
establish a connection and use the same.
if not,
then create database with some collections.
I am using mongoose, as mongoose is providing 3 methods to establish the connection. i am unable to figure out which is the best suite for me and how to deal with them.
connect
createConnection
connection
By googling i got succeed in figuring out whether the DB name exists or not using createConnection.
var Admin = mongoose.mongo.Admin;
var dbName='test';
/// create a connection to the DB
var connection = mongoose.createConnection('mongodb://localhost/' +dbName );
connection.on('open', function () {
// connection established
new Admin(connection.db).listDatabases(function (err, result) {
console.log('listDatabases succeeded');
for (var i in result.databases) {
if (result.databases[i].name == dbName) {
mongoose.connect('mongodb://localhost/' + dbName);
next();
break;
}
}
});
});
I wrote the above code in route interceptor, so for every request the above code will be executed and trying to connect to mongodb if the given db name already exists.
Any help would be greatly appreciable..

Resources