1
    TopicStatistics.methods.createTopicStatistics = function(callback)
    {
        // do stuff

        Topic.find({} , function (err, resultList)
        {
             if(err)
             {
                 // do stuff
                 if(typeof callback === "function")
                    callback(err); // callback undefined
             }
             else
             {
                 // do stuff
                 if(typeof callback === "function")
                    callback(null); // callback undefined
             }

        });
    };

Above is the code which I am trying to execute. The problem is this:

Since mongoose topic is asynchronous my function finalizes before the mongoose.find does its work which is normal and also because of this the callback variable is cleaned and it becomes undefined.

What I am looking for is a way to propagate the callback function to the mongoose.find function. Something like this:

Topic.find({} , function (err, resultList, mycallback);

that will enable me to use it inside my mongoose blob and to be able to call it when operations inside mongoose blob has ended.

2
  • 1
    Your first attempt should work IMO (without passing mycallback to Topic.find's function). If the callback is undefined it must be undefined. I.e. you're not passing anything to TopicStatistics.createTopicStatistics Commented Nov 1, 2014 at 4:51
  • you were right it was the function which I was passing incorrectly. Commented Nov 3, 2014 at 14:44

1 Answer 1

3

I think you need another callback defined in the scope of Topic.

Topic.find({} , function (err, resultList, callback)
    {

The "callback" variable you're using inside Topic.find() references back to the one set on TopicStatistics.createTopicStatistics(). So when you enter

Topic.find({} , function (err, resultList, mycallback);

the "mycallback" disappears since JavaScript doesn't check parameter count.

Sign up to request clarification or add additional context in comments.

3 Comments

I could not understand exactly what you have meant. Could you please give an example of the correct implementation?
I agree with laggingreflex above. I misread and thought you were defining Topic.find() in your example, but I see now that you were USING Topic.find() inside createTopicStatistics().
Some other things you might look at are the timings between when you create and save your mongoose models. To give a better answer, I would need to see more of your code to understand these timings. You might try referencing 'Topic' as this.model('Topic'). See the Mongoose docs (mongoosejs.com/docs/guide.html). There's an example under the heading 'Instance methods'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.