I am new to mongoDB and am currently working on setting it up using Node express server. I wonder how to manage concurrent mongodb requests to read collection data using the mongoose driver module.
For instance:
If 100 users access my server at the same time ( http://xxxxxx.com/showusers ), how will the mongodb connection work on the express server? Will it be one connection or divided into 100 connections, one for each request?
How can I close the connection object in mongodb effectively after the operation? Or can we leave the connection on the express server, as in the code below?
My code follows.
Server.js
var express = require('express');
var app = express();
app.set('port', config.port);
app.get('/users',storeusersapi.showUsers);
app.get('/storeUser',storeusersapi._insertUserDetails);
app.get('/findUser/:email',storeusersapi._findUser);
app.listen(app.get('port'),function(){
log.info('Express app started on port ' + app.get('port'));
});
storeusersapi.js
var mongoose = require('mongoose');
var log = require('../config/logger');
mongoose.connect('mongodb://localhost/mydb', function (error) {
if (error) {
log.error("MongoDB Connection failure - " +error);
}else{
log.info('MongoDB is connected Successfully!!!');
}
});
var Schema = mongoose.Schema;
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
var User = mongoose.model('users', UserSchema);
exports.showUsers = function(req,res){
User.find({}, function (err, docs) {
res.json(docs);
});
};
exports._insertUserDetails = function(req,res){
var object = new User({first_name:'bob',last_name:'sel',email:'sel@xxxxx.com'});
object.save(function (err) {
if (err) {
log.error('Insertion error - '+ err);
}
else {
log.info("User Stored into database!!!");
}
});
};
exports._findUser = function(req,res){
User.find({ email: req.params.email }, function (err, docs) {
res.json(docs);
});
};