Tuesday, 11 April 2017

Callback Issues - can someone debug my node js code? Can't update MongoDB

I'm a bit stuck and I can't figure out how to solve my problem. I'm using NodeJS, Mongoose.

Here is what I'm trying to accomplish: I have a users collection, an events collection, and a events.json file. I am trying to :

  1. Store the events in the JSON file in an array: "eventsCatalog"
  2. Go through each event "eventInstance" in "eventsCatalog" and associate it with a random user. To do that: Pick a random user "randomUser" from users collection, get his/her id, create author object, add author object to event.
  3. Add the eventInstance to the events collection in mongoDB.
  4. Update Random User. Add id of eventInstance to randomUser events array.

My code is not working. I'm assuming it has something to do with the asynchronous nature of mongoose methods.

function generateEvents() {
    fs.readFile(eventData, 'utf8', function (err, data) {
        if (err) { console.log(err); }
        eventCatalog = JSON.parse(data);
        updateDB();
    });
}

function updateDB() {
    console.log("Number of Events: " + eventCatalog.length);
    eventCatalog.forEach(function(eventInstance) {
        console.log("1"); 
        var rand = Math.floor(Math.random() * numUsers);
        User.findOne().skip(rand).exec(function (err, foundUser) {
            if(err) { console.log(err);    }
            console.log("2"); 
            var author = {
                 id: foundUser._id,
                 username: foundUser.username
            }
            eventInstance.author = author;
            Event.create(eventInstance, function(err, newEvent) { 
                 if(err) {console.log(err); }
                 console.log("3"); 
                 User.update(foundUser, {$push: {events: {_id: newEvent._id} }}, function(err, updatedUser) {
                    if(err) { console.log(err); }
                    console.log("4"); 
                    console.log(updatedUser);
                 });
            });
        });
    });

}

The reason I have the 1,2,3,4 is just to see whats going on. When I run this code, instead of getting 1,2,3,4 in order, I get:

1

1

... //more 1s

2

... //more 2s

3

... //more 3s

2

... //more 2s

3

... //more 3s

4

{ ok: 1, nModified: 0, n: 0 }

// A series of 4s and {ok: 1, nModified:0, n:0}

And obviously, nothing shows up in the events collection.

Would appreciate some guidance!



via Asool

No comments:

Post a Comment