Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
How to respect execution order in NodeJS application with mongoose

please help me understand how can I solve this.

this is my routes file (auth-routes.js)

const userControllers = require('../controllers/user')
module.exports = function(app){
  app.post('/auth/recuperarpassword', function(req, res){
    var info = userControllers.recuperarPassword(req, res)
    console.log('---------------->there is in routes file-->' + info);
    res.status(500).send(info)
  })
}

and this is my controller file (user.js)

    'use strict'
const User = require('../models/user')
const bcrypt = require('bcrypt-nodejs')
var momenttz = require('moment-timezone');
var mongoose = require('mongoose')
function recuperarPassword(req,res){
  var username = req.body.username.toLowerCase().trim();
  console.log('----username:---->' + username + '<---------------');
  var info;
    User.findOne({username: username}, function(err,user){
      console.log('Dentro del findOne');
      if (err) {
        console.log('--->Error - Error al buscar username en BD')
        return err
      }
      console.log('------>user:-->'+ user);
    })
  console.log('Salio del FinOne');
  info = {descerror: 'Elcomercio '}
  return info
}
module.exports = {
  recuperarPassword
}

and in the console results are printed like this:

----username:---->cesar4@mail.com<---------------
Salio del FinOne
---------------->Ya esta en routes-->[object Object]
POST /auth/recuperarpassword 500 42.647 ms - 27
Dentro del findOne
------>user:-->{ _id: 58fe681cb615c91f9d71adfb,
  username: 'cesar4@mail.com',
  password: 'hash',
  __v: 0 }

instead of printing in the correct order, something similar like this:

----username:---->cesar4@mail.com<---------------
Dentro del findOne
------>user:-->{ _id: 58fe681cb615c91f9d71adfb,
  username: 'cesar4@mail.com',
  password: 'hash',
  __v: 0 }
Salio del FinOne
---------------->Ya esta en routes-->[object Object]
POST /auth/recuperarpassword 500 42.647 ms - 27

Thanks!

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

your findOne function take time to fetch the data from database so it does not stop the flow of the execution of logic because :-

  • Node Js is Single thread is doesnt stop .All you can achive in callback functions.
  • Its is non-blocking I/O model

So , you can do it like this:-

    exports.recuperarPassword = function(req, res) {
        var username = req.body.username.toLowerCase().trim();
        console.log('----username:---->' + username + '<---------------');

        User.findOne({ username: username }, function(err, user) {
            console.log('Dentro del findOne');
            if (err) {
                console.log('--->Error - Error al buscar username en BD')
                return err;
            }
            console.log('------>user:-->' + user);
            console.log('Salio del FinOne');
            user.info= { descerror: 'Elcomercio ' }; //if you want to use info object

            return user; 
        });


};

All the things you want to be done just do it when result comes from database

about 4 years ago · Santiago Trujillo Report

0

You will need callback mechanism. NodeJS is event based nonBlockingIO. So your control will not stop till the DB call is executed hence your info variable is returned before you get result from DB

Let me know if you need more help on this.

Your controller function should look like this

'use strict'
const User = require('../models/user')
const bcrypt = require('bcrypt-nodejs')
var momenttz = require('moment-timezone');
var mongoose = require('mongoose')
function recuperarPassword(req,res, callback){
  var username = req.body.username.toLowerCase().trim();
  console.log('----username:---->' + username + '<---------------');
  var info;
  User.findOne({username: username}, function(err,user){
    console.log('Dentro del findOne');
    if (err) {
      console.log('--->Error - Error al buscar username en BD');
      callback(false);
      return err
    }
    console.log('------>user:-->'+ user);
    callback(user)
  });
}
module.exports = {
  recuperarPassword
};

Your route file should look like this

const userControllers = require('../controllers/user')
module.exports = function(app){
  app.post('/auth/recuperarpassword', function(req, res){
    userControllers.recuperarPassword(req, res, function(data){
      if(data === false){
        //there was error in your controller DB call
      }else{
        console.log('---------------->there is in routes file-->' + data);
        res.status(500).send(data)
      }
    });
  })
};
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!