Mongoose findone do not return values

Asked

Viewed 395 times

0

Guys, I’m having a problem here that I don’t know what else to try, I’m using express + Mongoose.

My model

let mongoose = require('mongoose');
let users = mongoose.Schema({}, {strict: true});
module.exports = mongoose.model('users', users);

My controller

const usersModel = require('../models/users.js');

exports.token = async (req, res) => {
    let data = req.body;
    if (data.email === undefined || data.email === null) {
       return res.status(400).json({msg: 'E-mail é obrigatório'});
    }
    var user = usersModel.findOne({email: data.email});
    console.log(user);
}

User return

model {
'$__':
InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5bf1a5b535ff0f0038cea73c,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths:
    StateMachine {
    paths: { __v: 'init', _id: 'init' },
    states:
    { ignore: {},
        default: {},
        init: { __v: true, _id: true },
        modify: {},
        require: {} },
    stateNames: [ 'require', 'modify', 'init', 'default', 'ignore' ] },
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter:
    EventEmitter {
    _events: [Object: null prototype] {},
    _eventsCount: 0,
    _maxListeners: 0 },
'$options': true },
isNew: false,
errors: undefined,
_doc:
{ __v: 0,
active: true,
password: 'sha1$0ff8d815$1$1ee620b675cd6f5f78f76c116023b9b00c5d79cc',
name: 'Nicolas',
email: '[email protected]',
_id: 5bf1a5b535ff0f0038cea73c },
'$init': true }

I don’t know what I’m doing wrong?

Thank you :)

2 answers

1

In the way you wrote it is as if you were associating the Documentquery to the variable. The correct way to get the result can be in two ways:

1 - As you have already used async in the function declaration, just put the await before usersModel.findOne({}).

2 - Declare a callback function, usersModel.findOne({},function(erro, user) {}).

I hope I’ve helped.

0

Probably missing the await.

If you gave the async, have to give the await to wait the query before displaying

Try it this way:

var user = await usersModel.findOne({email: data.email});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.