Problem to access elements of a document: mongoose

0

I want to do a password verification using express and mongoose.

All right until the part where I check the password, I just can not access that value of my document.

This is my function:

function iniciar_sesion(req, res)
{
  let usu = new Usuario({
    usuario : req.body.usuario,
    password : req.body.password
  })

  Usuario.findOne( {usu_nombre: usu.usuario}, (err, user) => {

    // Comprobar si hay errores
    if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})

    // Comprobar si el usuario existe
    if (!user) return res.status(404).send({message: 'No existe el usuario '})

    // Comprobar si la contraseña es correcta

    console.log(user._id) // marca su valor
    console.log(user.usu_contrasenia) // marca undefined
    console.log(user.usu_nombre) // marca undefined
    console.log(user)

    if (user.usu_contrasenia != usu.password)
      return res.status(400).send({message: 'Contraseña incorrecta'})

    // Genero token
    res.status(200).send(user)

  })

}

However, when I do the console.log (user) it prints the entire document:

{ _id: 586151481787e016382ee4b2,
  usu_nombre: 'John Doe',
  usu_contrasenia: '123' }

You should not be able to sign in by doing: user.usu_contrasenia ????????

The funny thing is that the _id does print it and it does correspond to the DB.

Any help?

Note: For now I am driving without encrypting the password, I wanted to do this test first but I do not get it o.O

    
asked by J.Correa 26.12.2016 в 21:01
source

1 answer

1

I already found the solution. Without the suggestions of @HectorSeguro I would not have made it.

What happens is that I tried to access those values as an attribute, but inspecting all the values of the users object with the code suggested by Hector (for (var s in user) {console.log (s);}) , I found the _doc method which returns the document as such.

user._doc

Then I can access the elements as follows:

user._doc.usu_usuario
user._doc.usu_contrasenia

Then my code remains:

'use strict'

const Usuario = require('../models/usuario.js')


function iniciar_sesion(req, res)
{
  let usu = new Usuario({
    usuario : req.body.usuario,
    password : req.body.password
  })

  Usuario.findOne( {usu_nombre: usu.usuario}, (err, user) => {

    // Comprobar si hay errores
    if (err) return res.status(500).send({message: 'Error al realizar la petición: ${err}'})

    // Comprobar si el usuario existe
    if (!user) return res.status(404).send({message: 'No existe el usuario '})

    console.log(user._doc.usu_usuario)
    console.log(user._doc.usu_contrasenia)

    if (user._doc.usu_contrasenia != usu.password)
      return res.status(400).send({message: 'Contraseña incorrecta'})

    // Genero token
    res.status(200).send(user)

  })

}

module.exports = ({
  iniciar_sesion
})

Thank you very much Hector again: ')

    
answered by 27.12.2016 / 00:15
source