How to check if there is an existing MongoDB connection using mongoose? - node.js

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);

Related

How to reuse existing mongo connection with mongoose?

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

Should I use both MongoDB and Mongoose in Node.js?

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.

Is mongoose.Types.ObjectId() an absolutely Node.js client-side operation?

I'm using the Mongoose next to the Node.js. The question is:
Does the following command for creation of the ObjectID value make a call to the server?
mongoose.Types.ObjectId()
I've checked my local MongoDB server log, and it doesn't show anything like a call to the single local MongoDB node/server for requesting a new ObjectID value. However, I'm not sure if the default server log is about all the operations(trivial and essential ops), or not!
NOTE: trivial ops here means the non-manipulative data operations!
A very simple script suggests that it does not make a call to the server:
Installing mongoose by running npm install mongoose
Then make a 2-liner index.js:
var mongoose = require('mongoose');
console.log(new mongoose.Types.ObjectId);
Because we haven't even connected yet.

Does Mongoose allow for Multiple Database Connections?

I read that in a nodejs application, if we use a mongoose object using
var obj = require('mongoose');
then, wherever we create a new mongoose object (say, in another file), then the same cached copy is used throughout. In that case, how can we connect to multiple database instances of mongoDB in the same nodejs app ?
You can use mongoose.createConnection to connect to a separate database, and then using the connection object that generates, you can define models from that database using connection.model.

How could I know if the mongodb is started or not by mongoose?

I have a working site with node.js + Express + mongoose.
I am afraid there will be chance that the MongoDB will be shut down by accident or maybe it wasn't started at first.
The following is the code:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/Test');
var Student = mongoose.model('student', new Schema());
Student.find({...},function(err,docs){
do sth
});
As I see , there will be no err message when find in no Mongo situation. It was just blocked.
And I didn't find a property in mongoose to show the connection status.
So anyone know how could I know the status of the mongodb in NodeJs?
The err parameter is a standard Error object which will be set if there any exceptions such as the database connection being unavailable. You do not need to check the connection status .. you need to check err and handle appropriately.
It would be worth having a read of the introduction to MongoDB's node driver for some example usage.
See also Error handling for Mongoose.

Resources