MERNG Stack Tutorial Video

Hello everyone,
I’m following the MERNG Tutorial from the freeCodeCamp Youtube channel.
But I’m stuck in the topic Register & Login Users.
By the timestamp 56:55 the instructor runs a query with GraphQL.
I’m getting this error message:

{
  "errors": [
    {
      "message": "Usuario validation failed: senha_usuario: Cast to string failed for value \"Promise { <pending> }\" at path \"senha_usuario\"",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "registrar"
      ],
    }
  ],
   [...]
  "data": {
    "registrar": null
  }
}

graphql/typeDefs.js

const gql = require('graphql-tag');

module.exports = gql`
  type Postagem {
    id: ID!
    conteudo_postagem: String!
    postagem_criada: String!
    nome_usuario: String!
  },

  type Query {
    getPostagens: [Postagem]
  },

  input DadosRegistro {
    nome_usuario: String!
    senha: String!
    confirmarSenha: String!
    email: String!
  },

  type Usuario {
    id: ID!
    email: String!
    token: String!
    nome_usuario: String!
    usuario_criado: String!
  },

  type Mutation {
    registrar(dadosRegistro: DadosRegistro): Usuario
  }
`

graphql/resolvers/usuario.js

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { UserInputError } = require('apollo-server');

// Chave para codificar o token
const { JWT_KEY } = require('../../config.js');
const Usuario = require('../../modelos/Usuario.js');

module.exports = {
  Mutation: {
    async registrar(_, { dadosRegistro: { nome_usuario, senha, confirmarSenha, email } }){

      // Checando se o usuario já existe
      const usuario = await Usuario.findOne({ nome_usuario })

      if(usuario){
        throw new UserInputError('Nome de usuário já existe', {
          erros: {
            nome_usuario: 'Este nome de usuário já existe'
          }
        })
      }
      
      // Criptografando senha
      senhaHashed = bcrypt.hash(senha, 12);

      const novoUsuario = new Usuario({
        nome_usuario,
        senha_usuario: senhaHashed,
        email_usuario: email,
        usuario_criado: new Date().toISOString()
      });

      const resultado = await novoUsuario.save();

      const token = jwt.sign({
        id: resultado.id,
        email: resultado.email_usuario,
        nome_usuario: resultado.nome_usuario
      }, JWT_KEY, { expiresIn: '1h' })

      return {
        ...resultado._doc,
        id: resultado._id,
        token
      }
    }
  }
}

I’ll wait for answers. Thank you.

This means that you want to have a string for senha_usuario in your Usuario model, but you don’t get one, because the Promise is pending, not fulfilled.

In your code, you can see that senha_usuario comes from senhaHashed.

sensaHashed comes from bcrypt.hash(senha, 12).

Looking at the docs of bcrypt, you can see that you have to do something with the hash function: either use then or await.

1 Like

Thank you! Your answer is really helpful, especially for me, I’m learning this stack for the first time.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.