Wednesday, 3 May 2017

Mongoose reacting differently to presence of callbacks

I was debugging a chunk of my Mongoose queries that I wanted to execute one after another to avoid inconsistency. After lot of trial, errors and tests, I finally stumbled upon a solution that seemed to work.

In one query, I include a query and in another, I skip including the callback function. The callback I am referring to is seen in the syntax of a Model.findByIdAndUpdate statement.

Model.findByIdAndUpdate(id, [update], [options], [***callback***])

The one which has a callback function executes perfectly and the one which doesn't, doesn't execute. It's encapsulated in a function which returns a mongoose promsise.

Here is the first query with the schema in Robomongo which adds an 'organiser' successfully:

function addUserToHackathonOrganisers(userId, hackathonId) {
    return Hackathon.findOneAndUpdate(
        {hackathonId: hackathonId},
        {$addToSet: {organisers: userId.toString()}},
        {new: true}
    );
}

Notice organisers Array[0] which indicates no update. enter image description here

Now, here is the query that works (with the callback in). In the attached image, you can see the organisers Array[1] which indicates that its updated.

function addUserToHackathonOrganisers(userId, hackathonId) {
    return Hackathon.findOneAndUpdate(
        {hackathonId: hackathonId},
        {$addToSet: {organisers: userId.toString()}},
        {new: true},
        function (err) {
            if (err) {
                console.log(err);
            }
        }
    );
}

enter image description here

I'm clueless why this happens. Any ideas?



via bholagabbar

No comments:

Post a Comment