Reputation: 9417
I'm not sure if I am on the right track, but this is what I have...
router.post('/login', function(request, response) {
User.find({ 'username': request.body.email,'email':request.body.pwd }, function(err, user) {
//do not know what to add here
I am taking POST
data from two input fields and then using find
command to check if this field already exists in my mongo database.
User
is the model schema I created. It looks as so...
var Schema = new mongoose.Schema({
email : String,
password : String,
display : String
});
var User = mongoose.model('User', Schema);
I think I am on the right track but I am not sure what to add inside the find
command. If both fields exist together, I want to do one thing, if they don't I want to throw an error, how can I do this?
Upvotes: 2
Views: 11479
Reputation: 631
You are using find in your query, meaning you are trying to find ALL matching users, and expecting an array of users from the mongodb.
If none found, the user variable will be an empty array.
If you just want to let the browser know that the request was fine, password matched the database record and the user was found, you can do something like:
router.post('/login', function(request, response) {
User.find({ 'username': request.body.email,'email':request.body.pwd },
function(err, user) {
//do not know what to add here
if (user.length === 0) {
return response.status(403).send("Unauthorized");
}
return response.status(200).send("OK");
}
P.S. Also, you can use mongoose findOne query for the purpose of user login.
Upvotes: 2
Reputation: 2214
I suggest using findOne
over find
, as it will return a single document if it exists, otherwise null
.
router.post('/login', function(request, response) {
// use `findOne` rather than `find`
User.findOne({
'username': request.body.email,
'email':request.body.pwd }, function(err, user) {
// hanlde err..
if (user) {
// user exists
} else {
// user does not exist
}
})
})
Upvotes: 7