Bim Bam
Bim Bam

Reputation: 439

Why page ain't redirecting, when query can't find user?

Why when the request does not find the user, then he hangs, instead of making a redirect to the main page? How can this be remedied?

            User.findOne({_id: userid}, function(err, user) {
                if(err) {
                    res.redirect('/');
                }
                if (user) {
                    res.render('user',{
                        title: user.nickname,
                        id: user._id,
                        nickname: user.nickname,
                        email: user.email,
                        name: user.name,
                        surname: user.surname,
                        age: user.age,
                        country: user.country,
                        city: user.city,
                        phoneNumber: user.phoneNumber,
                        myId: req.user._id
                    })
                }
            });

Upvotes: 0

Views: 35

Answers (2)

A Hobbit
A Hobbit

Reputation: 62

You only redirect if the request has an error. If you have no error and there is no user, nothing will happen. If findOne doesn't find a match, it will return an empty document, not an error.

Try changing the first if statement to:

 if(err || !user) {
   res.redirect('/');
 }

Upvotes: 1

Javier Conde
Javier Conde

Reputation: 2593

Because not finding anything is different than having an error, try the following:

User.findOne({_id: userid}, function(err, user) {
            if(err || !user) {
                res.redirect('/');
            }
            else {
                res.render('user',{
                    title: user.nickname,
                    id: user._id,
                    nickname: user.nickname,
                    email: user.email,
                    name: user.name,
                    surname: user.surname,
                    age: user.age,
                    country: user.country,
                    city: user.city,
                    phoneNumber: user.phoneNumber,
                    myId: req.user._id
                })
            }
        });

Upvotes: 2

Related Questions