0

I am having my code as

function updateData(data){
    data.forEach(function(obj){
        users.find({_id:obj.userId}).toArray(
        function(e, res) {
            obj.userData = res;
            console.log(res)
        }); 
    });
    return data;
}

The problem is I am unable to find the updated data, I am trying to update my data and adding one more field to it based on userId. The data parameter is an array containing the output from comments table. hope you understand the scenario.

0

1 Answer 1

1

It looks that users.find({...}).toArray(function(...){...}) is going to be asynchronous, so there is no way that you can be sure that the db call has been completed and that each data.obj has been updated before data is returned.

Instead of using the javascript Array.prototype.forEach() function, you could use the NodeJS async.each function from the async library by Caolan which would iterate through the array, update each object and then return the data object only when all functions calls have completed.

For example:

var async = require("async");

function updateData(data){
    async.each(data, function(obj, callback) {
        users.find({_id:obj.userId}).toArray(
            function(e, res) {
                obj.userData = res;
                callback(e);
            }
        );  
    }, 
    function(error){
        return data;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Still getting the same result. I am new with Node.js callback pattern. can you please provide some reference where I can I find more stuff to understand this whole pattern??
There is a section called "What are callbacks?" in this tutorial. If you are feeling adventurous then there is this article about "Callback Hell" and how to avoid it. Do your console log messages show up in your terminal? You should also check e to see if an error is being returned

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.