Bolboa Bolboa - 1 year ago 72
Javascript Question

Multiple connection error when using node js and mongodb

I'm using the following schema located in my


var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var userSchema = new Schema({
username: String,
password: String,
name: String,
last: String,
year: Number,
degree: String


var User = mongoose.model('User', userSchema);

module.exports = {
User: User

In my
file I am storing some information using POST data...

var User = require('../routes/schema').User;

exports.postRegister = function (req, res) {
var u = new User({
username: req.body.reg_username,
password: req.body.reg_password,
name: req.body.reg_name,
last: req.body.reg_lastname,
year: req.body.reg_year,
degree: req.body.reg_degree
}); (err) {
if (err) {
throw err;
else {
res.render('index', { title: 'Express' });


Everything gets saved fine in my Database. But now, this
file redirects the user back to
where the user must then sign in using some credentials stored in the database.

So in my
file I need to check if username and password exist together in a collection in my database, I tried the following...

var User = require('../routes/schema').User;

exports.signin = function (req, res) {
username: req.body.log_username,
password: req.body.log_password
}, function (err, docs) {
if (docs.length) {
console.log("name exists");
else {
console.log("no exist");

I used the
function with the same Schema to check if username and password exist in a collection in the database, but it doesn't work properly. I seem to get a multiple connection error and I do not know how to avoid it.

When I try to login using some credentials already in the database, the console prints out
no exist
meaning the else statement in
is reached.

Answer Source

try it docs.length !== 0 this is check docs field is existed or empty.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download