Reputation: 1093
I am developing Nodejs application with express and mongodb. I added data to mongodb but when i try find method. It is not working. Could not catch exception. So my code is shown below:
var routes = function (app) {
app.locals.error = null;
app.get('/login', function (req, res) {
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login'
});
});
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/fuatblog");
var UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
age: Number
}),
Users = mongoose.model('Users', UserSchema);
app.post('/sessions', function (req, res) {
console.log(req.body.user.email);
console.log(req.body.user.password);
Users.find({
email: req.body.user.email,
password: req.body.user.password
}, function (err, docs) {
if (err) {
console.log('User Not Found');
res.status(400);
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login',
error: 'Email or password is wrong.'
});
}
console.log('User found');
req.session.email = docs[0].email;
console.log(req.session.email);
});
return res.redirect('/Management/Index');
});
};
module.exports = routes;
After i posted wrong email and wrong password data from login.jade to /sessions. This code should run:
if (err) {
console.log('User Not Found');
res.status(400);
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login',
error: 'Email or password is wrong.'
});
But it passed this if statement, always. So inside of 'if' not running. 'err' variable always false. Why ? There is no user with this email and password in my mongodb database. Need advise. Sorry about grammer. Sorry for the grammar
Upvotes: 1
Views: 1315
Reputation: 3718
I think when you try to find an entry in your database and it is not found, this won't genrate error it just will return an empty result set
So you can check on the size of the returning result instead of checking if there's an error
if(docs.length == 0){
console.log('Not found')
}
Upvotes: 1
Reputation: 203231
It's not an error if a query doesn't match any documents in the database; you have to check docs
to see if there are any matching documents:
if (! docs.length) {
// no results...
}
The err
argument is only set in situations where an error occurred during the execution of the query (you passed an invalid query, the database is offline, etc).
Upvotes: 2