Saturday, 20 May 2017

Why mongoose query with promise always goes to .then block rather than .catch

my User collection have one user and that is inactive but when I query to find out the user which is Exist and Active, I am using mongoose 4.x with promise (see below query) , it always goes to .then block and display blank array but in my understanding, it must go to .catch()block.

Please correct me and suggest how to write the right query.

Schema

let userSchema = new Schema({
    username: {type: String, required: true, unique: true},
    password: {type: String, required: true},
    firstName: {type: String, required: true},
    lastName: {type: String},
    email: {type: String, required: true},
    gender: {type: String, enum: ['M','F'], default: 'M'},
    passwordReset: {type: Boolean, default: false},
    isActive: {type: Boolean, default: false},
    createdOn: {type: Date, default: Date.now}
});

query

User
            .find()
            .and([{username: req.body.username}, {isActive: true}])
            .exec()
            .then( (user) => {
                    console.log('user found', user );
                    // match saved and input password
                    if (user.password === req.body.password) {
                        res.status(200).json(user);
                    } else {
                        console.log('else part', user);
                        res.status(404).send({
                            "message": "invalid credentials."
                        });
                    }
                }).catch( (err) => {
                    console.log('catch error', err);
                    res.status(404).send(err);
                });
        }



via pro.mean

No comments:

Post a Comment