wmik
wmik

Reputation: 784

Mongoose returning string instead of object

I am experiencing a slight issue while trying to query mongodb using mongoose. Here is a sample of my code:

...
resolve: (root, params) => {
  var user = User.findOne({email: params.data.email}).exec()
  return user;
}
...

This returns the following:

{
  "data": {
"login": "{ _id: 596f4cc4f51fa12bf0f5a001,\n  updatedAt: 2017-07-19T12:12:52.736Z,\n  createdAt: 2017-07-19T12:12:52.736Z,\n  email: '[email protected]',\n  password: '$2a$12$bhPG4TPGR6by/UBTeAnzq.lyxhfMAJnBymDbkFDIHWl5.XF2JG62O',\n  __v: 0 }"

} }

I have no idea why this is happening. Any help would be appreciated.

EDIT
Here is the full code :

var bcrypt = require('bcryptjs');
var _ = require('lodash');
var { GraphQLNonNull, GraphQLString } = require('graphql');
var jwt = require('jsonwebtoken');

var { UserInputType } = require('./UserSchema');
var User = require('./UserModel');

var login = {
  type: new GraphQLNonNull(GraphQLString),
  args: {
    data: {
        name: 'Data',
        type: new GraphQLNonNull(UserInputType)
    }
  },
  resolve: (root, params, { SECRET }) => {
    var user = User.findOne({email: params.data.email}).exec();
    var authorized = bcrypt.compareSync(params.data.password, user.password);
    if (!authorized) throw new Error('Invalid password');
    var token = jwt.sign({
        user: _.pick(user, ['_id', 'name'])
    }, SECRET, {expiresIn: '1y'});
    return token;
  }
};

Upvotes: 0

Views: 1023

Answers (2)

wmik
wmik

Reputation: 784

resolve: (root, params, { SECRET }) => {
    return new Promise(resolve => {
        User.findOne({email: params.data.email}).exec().then(user => {
            bcrypt.compare(params.data.password, user.password, (err, authorized) => {
                if (!authorized) throw new Error('Invalid password');
                var token = jwt.sign({
                    user: _.pick(user, ['_id', 'name'])
                }, SECRET, {expiresIn: '1y'});
                resolve(token);
            });
        });
    }).then(token => token);
}

Decided to do this instead and voila! Solved my issue. Thanks for the help.

Upvotes: 0

Mustehssun Iqbal
Mustehssun Iqbal

Reputation: 566

This might be in the function which calls resolve and calls .then of this user promise. Can't tell for sure without more code...

Upvotes: 1

Related Questions