I am learning to use the mongodb native driver along with nodeJS and ExpressJS. I am new to NodeJS so please bear with me.
The UI CLIENT sends data to the REST API endpoint and the POST call inserts the data (document) into MongoDB collection.
When I am going through the examples at MongoDB native driver documentation, I notice that collection.insertOne
, collection.save
are always performed as a callback to the mongo_client.connect
. I don't understand this because I want to connect to mongo_client once and continue to update the collection and bring down the connection (mongo_client.close) when the express server is brought down. I understand that callbacks are safe.
const client = new MongoClient(url, {useNewUrlParser: true});
// Use connect method to connect to the server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
Why do I have to connect for every CRUD operation? save the state of the connection to the db/collection and cannot reuse?
My existing code:
const express = require('express')
const app = express()
const server_port = 64726
const MongoClient = require('mongodb').MongoClient;
const insert_user = (id, email)=> {
mongo_client.connect(err => {
console.log("mongo connect function called....")
assert.equal(null, err)
console.log ("connected successfully to DB ")
const mongo_user_collection = mongo_client.db(mongo_db_name).collection("users");
mongo_user_collection.save ({'_id':id,'email':email,'lastlogin': new Date() })
// perform actions on the collection object
// mongo_client.close();
});
}
app.post ('/api/login/verify', (req, res) => {
insert_user(req.body.id,req.body.email);
})
app.listen(server_port, ()=>{
console.log('Server started...')
})
In my code, I see for every post call I need to connect and then insert the document. How to avoid this behavior so I can Connect once, reuse connection and insert docs for every POST call?