Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

451
Visualizações
Callback function with Nodejs + Mongoose, How to return only the search value?

I already researched how to do this, but I still can not understand, where am I going wrong ? I researched how to do this type of function but I could not understand how to get an answer in my callback, always end up having 2 functions within the other.

Controller UserCtrl

    // Models
    var User = require('../models/user');

    var isUserSearch = function(email,callback){

        User.find({email:email},function(err,data){
            if(err) throw err;
            return callback(data);
        });

    }

    var isUser = function(email){

        var resp = isUserSearch(email,function(data){
            return data;
            console.log(data); // I get my data 
        });

        console.log("Response : " + resp); // undefined

        return resp;

    }

    var result = {
        gerarToken : gerarToken,
        isUser : isUser,
    }

    module.exports = result;

Model

// Model
var mongoose = require('mongoose');

// Schema
var Schema = mongoose.Schema({
    name : {
        type : String,
        require : true
    },
    email : {
        type : String,
        require : true,
        unique : true
    },
    password : {
        type : String,
        required : true
    },
    type : {
        type : Number,
        required : true,
        default : 1
    },
    created : {
        type : Date,
        default : Date.now
    }
});

var Data = mongoose.model('User', Schema);

module.exports = Data;

Context AuthCtrl

// Controllers

var Crypto = require('./cryptoCtrl');

var User = require('./UserCtrl');

// ----------- Login
var login = function(req,res){
    var data = req.body;
    var email = data.email;
    var password = Crypto.cryptoString(data.password);

    var existUser = User.isUser(email);

    if(existUser){

        // IsUser is a function to return the user array 
        // if it exists, otherwise it returns only a false 
        // boolean value. In the example I'm going to use this function

    }


}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

var resp = isUserSearch(email,function(data){
  return data;
  console.log(data); // I get my data 
});

console.log("Response : " + resp); // undefined

resp is undefined due to non-blocking asynchronous architecture node.js provide.

The line which you are trying to logging the value is executed when the function that return the data isUserSearch has not already finished.

Did you already try to call isUserSearch rather than isUser in you controller?

var login = function(req,res){
    var data = req.body;
    var email = data.email;
    var password = Crypto.cryptoString(data.password);

    User.isUser(email, function(existUser) {
       if(existUser){
          console.log('User exist', existUser);
        // IsUser is a function to return the user array 
        // if it exists, otherwise it returns only a false 
        // boolean value. In the example I'm going to use this function
       } else {
          console.log('User does not exist');
       }
    });
}

Then you can remove isUser and change:

var result = {
    gerarToken : gerarToken,
    isUser: isUserSearch,
}
over 4 years ago · Santiago Trujillo Relatório

0

You only need the isUserSearch function with the callback. Use the data returned in a callback in the AuthCtrl and you call this as:

Controller UserCtrl:

// Models
var User = require('../models/user');

var isUserSearch = function(email, callback){
    /* use findOne() which returns a single document that you can check if null */
    User.findOne({email: email}, function(err, user){ 
        if (err) throw err;
        return callback(!!user); // return a callback with a Boolean value as argument
    });
}

var result = {
    gerarToken : gerarToken,
    isUser: isUserSearch,
}

module.exports = result;

Context AuthCtrl:

// Controllers

var Crypto = require('./cryptoCtrl');

var User = require('./UserCtrl');

// ----------- Login
var login = function(req, res){
    var data = req.body;
    var email = data.email;
    var password = Crypto.cryptoString(data.password);

    /* Call the isUser function with a callback */
    User.isUser(email, function(userExists){
        if (userExists) {
            // userExists is a boolean value
        }
    });

}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda