Bolboa Bolboa - 5 months ago 17
Javascript Question

Multiple connection error when using node js and mongodb

I'm using the following schema located in my

/routes/schema.js
file...

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
/routes/register.js
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
});

u.save(function (err) {
if (err) {
throw err;
}
else {
console.log("saved");
res.render('index', { title: 'Express' });

}
});
}


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

So in my
index.js
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) {
User.findOne({
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
findOne
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
exports.signin
is reached.

Answer

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