In my nodejs application I have connection created to mongodb using the MongoDB driver.
const client = await mongodb.MongoClient.connect(connectionString)
This works fine. But now I am trying to reuse the same connection with Mongoose, using the setClient() function as mentioned in the docs:
https://mongoosejs.com/docs/api/connection.html#connection_Connection-setClient
const conn = mongoose.createConnection().setClient(client);
conn.readyState; // is 1 which indicates CONNECTED
But when I try to run query using Mongoose models like:
const data = await MyModel.find()
I get a buffering timed out after 10000ms error
Is this the correct way of using a existing mongo connection?
Alternative approaches welcomed as well
Related
I am new to MongoDB and I use MongoDB locally but in some cases I need to use Mongoose. How to use both MongoDB and Mongoose in the same project. Please help me to resolve this issue and please put if you have any references.
MongoDB is a database, while Mongoose is the "bridge" between MongoDB and your server. You use it to create schemas and connect to MongoDB. Please see this for more in depth answer for your question.
yes you should, its a good practice.
npm install mongoose
Mongoose requires a connection to a MongoDB database. You can use require() and connect to a locally hosted database with mongoose.connect().
//Import the mongoose module
var mongoose = require('mongoose');
//Set up default mongoose connection
var mongoDB = 'mongodb://127.0.0.1/my_database';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
//Get the default connection
var db = mongoose.connection;
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
If you need to create additional connections you can use mongoose.createConnection(). This takes the same form of database URI (with host, database, port, options etc.) as connect() and returns a Connection object)
Mongoose is a full package, it has all the methods required by a backend. It has a connections function, it has ORM which helps to do CRUD operations. It is like an industry standard.
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
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.
I am trying to connect to my mongoDB atlas cluster but get an authentication fail.
I am able to connect from a client like Studio 3T and from the Mongo shell.
Here's my connection URI:
var conn = mongoose.connect("mongodb://<user>:<password>#xxx-shard-00-00-kqmqb.mongodb.net:27017,xxx-shard-00-01-kqmqb.mongodb.net:27017,xxx-shard-00-02-kqmqb.mongodb.net:27017/myDB?ssl=true&replicaSet=xxxCluster-shard-0&authSource=admin")
I copied this from the atlas console.
I'm using Mongoose 4.9.7 which uses MongoDB 2.2.26 so I'm using the latest versions of these modules.
The error I get is the following:
MongoError: authentication fail
Any idea what this could be?
Found the solution. My password has special characters so I have to encode it properly. Changed the implementation to
var f = require('util').format;
var user = encodeURIComponent('user');
var password = encodeURIComponent('p#ssw0rdWithSpecialCharacter');
var url = f("mongodb://%s:%s#xxx-shard-00-00-kqmqb.mongodb.net:27017,xxx-shard-00-01-kqmqb.mongodb.net:27017,xxx-shard-00-02-kqmqb.mongodb.net:27017/myDB?ssl=true&replicaSet=xxx-shard-0&authSource=admin",user,password);
var conn = mongoose.connect(url);
I have an express app that connects to MongoDB via mongoose, and I also have an init script that will occasionally connect to MongoDB.
Is there any way to detect if there is an existing connection to the DB, so I will not need to connect again in the script anytime I want to run it, also is there any consequences for connecting to the DB multiple times via mongoose.
you can check this using mongoose.connection.readyState,
ex.
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);
The state would return 1 if already connected.
You can check the readyState
var mongoose = require('mongoose');
console.log(mongoose.connection.readyState);