0

I'm fetching some data from the data base and when I get that data I just want send some few attributes not the whole row. So for it I'm using a method 'pick' from underscoreJS. But problem is, when I apply this method and pass the object to response (res.status(200).json(obj.toJSON()), instead of getting this object I'm getting the error message. Here is my code.

This is auth.js => Here I'm applying the 'pick' method and sending it.

const bcrypt = require('bcryptjs');
const db = require('./db.js');
const _ = require('underscore');

    module.exports = function(body) {
      return new Promise((resolve, reject) => {
        db.users.findOne({where: { email: body.email}}).then((user) => {
          if (bcrypt.compareSync(body.password, user.get('hashed_password'))) {
            let publicDetails = user.toJSON();
            publicDetails = _.pick(publicDetails, 'id', 'email');
            resolve(publicDetails);
          } else {
            reject();
          }
        }).catch(() => {
          reject();
        });
      });
    }

Here, in this file I'm calling that promise.

 app.post('/users/login', (req, res) => {
      const body = _.pick(req.body, 'email', 'password');

      auth(body).then((user) => {
        res.status(200).json(user.toJSON());
      }).catch(()=>{
        res.status(401).send();
});
devashish-patel
  • 663
  • 1
  • 7
  • 15
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jul 04 '17 at 00:15
  • 1
    "*I'm getting the error message*" - which error message? – Bergi Jul 04 '17 at 00:18
  • Like if it finds the value, still gives status 401 and if in auth.js I put 'user' instead of 'publicDetails' it works fine. – devashish-patel Jul 04 '17 at 04:53
  • 1
    Ah, I see now. You're calling `.toJSON()` twice, once in auth.js and once in the main file. That'll throw an exception of course, as the plain object doesn't have any such method. You should set up logging for the exceptions that you `catch`, it would have been obvious with the error message! – Bergi Jul 04 '17 at 05:01

0 Answers0