Should I use both MongoDB and Mongoose in Node.js? - 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.

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

How Can I populate some Collections in MongoDB only in the first time

I'm using NodeJs as backend and MongoDB as a database along with mongoose.
I want to populate one of my collections named Users only for the first time that the application runs.
My goal is to add one user to users collection automatically in the first time that application run.
(this subject is known as migration in ASP.NET And EntityFramework).
How can I achieve that in Nodejs?
Well that's kindda easy, you just need to wait for mongoose to connect to your database then put your code in the event listener for the database connection.
check out the example straight out of mongoose docs
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// You can put your code here
});
NOTE: there might be connection interruption and mongodb gets disconnected and reconnected (this happens manually), you need to put a flag to make sure you don't populate your database unwillingly after reconnection.

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

How to check if there is an existing MongoDB connection using mongoose?

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

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