Two node.js applications connected to the same mongodb database - node.js

I have two node.js applications, both of them should connect to the same mongodb database. I should insert document in one application and retrieve it from the other application. I added the same connection of the database to both application. My database is on localhost.
var MongoClient = require('mongodb').MongoClient;
var MONGO_HOSTS = {
undefined: 'localhost:27017',
'development': 'localhost:27017',
'test': 'localhost:27017',
'staging': process.env.MONGO_HOST,
'production': process.env.MONGO_HOST
};
// Connection URL
var url = 'mongodb://' + (process.env.MONGO_HOST || MONGO_HOSTS[process.env.NODE_ENV]) + '/test' + process.env.NODE_ENV;
Then connect to the database. The problem is that when I insert in one application the other application don't find it. Is this valid way of connection or is there other way.

Communicating via database is not the best pattern. But if you would like to do that, make sure you're trying to read data from DB after write was successful. Try also finding that document using first DB to make sure that your 'find' query is working.

Related

How to connect to mongodb atlas cluster to create new database using node js [duplicate]

I'm using node.Js, expressjs mongodb and Atlas
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
the above method is not working for me.
by using atlas database. you are given three nodes with three different host/Url now the problem here is that when I try to connect to mongodb.server it only ask for one host name (or its allowed to add many but I just don't know how)
my question would be, how can I make this work? like how can I join together 3 different Url and let 1 port let it in. and connect to database server
you are given three nodes with three different host/Url now the problem here is that when I try to connect to mongodb.server it only ask for one host name
MongoDB Atlas provides you with a MongoDB Connection URI. The connection string should contain host(s) information.
You can also see a snippet example of MongoDB Node.js connecting to MongoDB Atlas on the manual MongoDB Atlas: Node.js Driver Example
MongoClientURI uri = new MongoClientURI(
"mongodb+srv://user:password#cluster0.mongodb.net/");
MongoClient mongoClient = new MongoClient(uri);
MongoDatabase database = mongoClient.getDatabase("databaseName");
MongoDB Version 3.4 and earlier:
var MongoClient = require('mongodb').MongoClient;
var uri = "mongodb://user:password#mycluster0-shard-00-00.mongodb.net:27017,mycluster0-shard-00-01.mongodb.net:27017,mycluster0-shard-00-02.mongodb.net:27017/admin?ssl=true&replicaSet=Mycluster0-shard-0&authSource=admin";
MongoClient.connect(uri, function(err, db) {
db.close();
});
For other drivers, please see MongoDB Atlas: Connect via Driver

Create a dedicated Database per user in a MEAN App

I am working on a project that requires a dedicated database per registered user. I prefer working with MongoDB so I'm using that for the same (Am I Right?). The app uses a REST API as the backend (written in Node Express) and an AngularJS App. So, what I think of doing is whenever a user makes a request to some API endpoint say, a GET request to api/user/mydata, I would create a connection to his particular database, fetch the required data, close the connection and return the fetched data as the response. Is this approach correct? Also, I'm using Mongoose as the ODM and PassportJS for user Authentication. Moreover, users of my app are mutually exclusive. There is no data connection between a user with any other registered user.
There's a way to do that but only without using Mongoose. You would have to create a root connection to your MongoDB server (mind it, not to a particular database on that server) using the mongodb node module and then you can switch between the database as per your query requirement without creating a new connection per database as shown below:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// URL to the root of MongoDB Server and not a particular db
const url = 'mongodb://localhost:27017';
// Database Names
const dbName1 = 'myproject1';
const dbName2 = 'myproject2';
// 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 db1 = client.db(dbName1);
const db2 = client.db(dbName2);
client.close();
});
You can't do this through mongoose, as mongoose and its models require connection to be made to a particular database and not to just the root db server. Anyways, I didn't want to give up mongoose for my own project so I just had to resort to initializing the db connection and its models per HTTP request by the user and closing the connection upon response.

Mongodb Monk reauthentication on connection

I have a node program connecting to a MongoDB. Theres a production server where we do proper authentication to connect to the db, but during development on our local machines it's just more tedious to keep track of authentication, especially because most of the time we completely wipe the db often. So resetting up authentication becomes even more tedious. So my solution was to attempt to connect to the db securely, and then if it fails then try to connect to the db in the dev fashion. Heres the code:
var db = require('monk')('username:password#localhost/TESTR', {authSource:'admin'});
db.catch(function(err) {
clog.i("MONGO AUTHENTICATION FAILED, USING NO AUTH CLIENT");
db = require('monk')('localhost/TESTR')
});
The problem is that this doesn't work. The rest of the app just complains about the authentication failure the first attempt had. Is there a better solution to this? Or am I just a moron?
var monk = require('monk');//layer used to connect mongodb
var db = monk('*****:27017/TESTR');
var collection = db.get('collection_name');
//you can access your collection using the mongo query
//simple controller action
module.exports = function(req, res){
collection.find({}, function(err, cb){
if(err) {res.json("db exception");}
else{res.json(cb)//it returns the db collections}
};
}

What is the correct URL schema for connecting to mongodb with multiple databases

Setting up a new project, I wanted to have separate databases for test, dev and prod:
d:/mongodb/project/test
d:/mongodb/project/dev
d:/mongodb/project/prod
I got these up with mongod --dbpath d:/monodb/project/<env>
When I try to connect I get Error: More than 1 database name in URL
const { MongoClient } = require('mongodb')
MongoClient.connect('mongodb://localhost:27017/project/dev')
The example given in the api docs doesn't help much
var MongoClient = require('mongodb').MongoClient,
test = require('assert');
// Connection url
var url = 'mongodb://localhost:27017/test';
// Connect using MongoClient
MongoClient.connect(url, function(err, db) {
What is the correct specification for the url connection? (Or, if I am going about this the wrong way entirely, what is the best way to separate databases for testing?)
You can connect to mongodb using this driver as instructed in their documentation:
http://mongodb.github.io/node-mongodb-native/2.2/quick-start/quick-start/
So the URL you have there is correct.
If you want to have separate databases (which could also be on different hosts with different credentials) then I suggest you use a config package:
https://www.npmjs.com/package/config
This allows you to define a configuration for each environment where default will be a catch all if environment variable cannot be matched to a json file. In other words, NODE_ENV=prod would map to prod.json, NODE_ENV=test would map to test.json and NODE_ENV=[empty] would map to default.json. This is one possible setup.
You definitely don't want to create multiple connections for each environment. This is not necessary.

How can I connect to multiple MongoDB databases using monk?

I have a Node.js application with 2 modules, each of which have their own database.
I'm using monk to connect to these databases, can they each connect to their own database, or am I limited to only one DB connection per app?
This code is used in both modules:
var mongo = require('mongodb');
var monk = require('monk');
...
module.exports = function(modules) {
...
var StorageClass = function() {
var myDb;
this.init = function() {
console.log('Connecting to Mongo DB on %s', config.database.URL);
myDb = monk(config.database.URL);
}
...
}
var storage = new CatchupStorageClass();
storage.init();
return storage;
}
Looks like when this code is executed in the second module, it wipes out the configuration for the first module and replaces it with its own. These 2 modules does not even use a shared storage class, they each have their own (duplicated) copy with a different name.
How is it possible to have more than one connection in a Node.js app? Does monk support it?
Yes, monk does support connections to different database in the same app.
My problem was coming from incorrect use of multiple base strategies in passportjs.
I simply needed to name my different base strategies separately: Use multiple local strategies in PassportJS

Resources