Your code should works.
You need to check if the problem is not from another place.
An example :
var Schema = require('mongoose').Schema;
var userSchema = new Schema({
uname: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = require('mongoose').model('User', userSchema);
var User = require('pathToUserModel');
app.post('/login', function(req, res) {
User.findOne({
uname: req.body.uname,
password: req.body.password
}, function(err, user) {
if (err) { return res.status(500).send(err); }
if (!user) { return res.status(200).send("User not found"); }
return res.status(200).send("You are logged in succesfully.");
}
});
});
<form action="/login" method="POST">
<input type="text" name="email" placeholder="your email">
<input type="password" name="password" placeholder="your password">
<input type="submit" value="submit">
</form>
You need to check if you have the user stored in your database or it will not works. To do that you can access your database in command line :
- Open a command line prompt
- type
mongo
- type
use nameOfYourDB
You need to replace nameOfYourDB
by your database name
- type
db.users.find()
: users is the name of your collection
Then you can see what is stored in your DB.
Your database should also be started on your system with mongod
and your app should be connected to the database with something like require('mongoose').connect('mongodb://127.0.0.1/nameofYourDB', { /* options */ });
(still need to replace nameOfYourDB).
You should keep in mind that it is just an example to understand the logic. In production you should do more work as validate form, hash passwords with a salt and a derivation function etc.