0

I have a problem with node.js callback function.

This is my postProcessing.js file.

var express = require('express');
//create router like interface for responce  to app.js
var router = express.Router();
//Inject mongoose in context
var mongoose = require('mongoose');
//Create Mongoose Schema object
var Schema = mongoose.Schema;


router.get('/', function(req, res, next) {

  var radnikProjId = new Array();

  function make(callback) {

        mongoose.model('radprojcol').find({'mbr': 50}, function(err, radproji) {
            radproji.forEach(function(radproj){
            mongoose.model('projekatcol').findOne({'spr': radproj.spr}, function(err, projekat) {

              radnikProjId.push({'id':projekat._id});

            });

            });
          });

          return callback(radnikProjId);

}

  make(function(resp){
    console.log(resp)
  });

});

module.exports = router;

When I call make function it returns an empty document.

But when I call callback in most inner foreach it returns a good document, with all I need.

What is wrong with this code, can any one help me?

I exprected that my radnikProjId array variable going to be fulfilled with objects in time when I call a callback inside of make function.

Thak you.

branko terzic
  • 654
  • 1
  • 8
  • 27
  • 3
    Your `callback(radnikProjId)` is outside the `.findOne` callback, which means it execute before `.findOne`'s callback been executed. – nightire Jun 27 '15 at 15:25
  • Thank you nightire, i released it now. How can i implement this make function to be sure, that at the end of the function all other callbacks are executed, and my radnikProjId variable fulfilled? – branko terzic Jun 27 '15 at 17:52

0 Answers0