israel
israel

Reputation: 57

Wait for mongoose exec to finish

I have an issue with a performing a query with moongose and NodeJS

I am trying to perform a search with moongose and depends on the result assign it to a variable but when i print the variable it shows as empty

  let queryDict;

  query.exec(function (err, item) {
    if (err) return handleError(err);
    if (item === null || item.length === 0) {
        queryDict = { 
            status: 'empty',
            comment: 'some comment' 
        };
    }
    else { queryDict = item }
});

console.log(`queryDict: ${queryDict}`);

The expected behavior is to have some content in the variable. please help me to accomplish this

Upvotes: 0

Views: 1620

Answers (1)

Nick Tomlin
Nick Tomlin

Reputation: 29221

Mongoose operations are asynchronous, so queryDict will be undefined when your console.log statement executes.

You will need to move your console.log into the body of the callback you've provided to be able to access the value from your query.

Don't worry if that seems a bit confusing, the asynchronous nature of JavaScript is easy to trip up on if you are new to the paradigm. I'd recommend reading the article linked above and playing around with the examples in the mongoose docs.

Alternately, you could rewrite this using async/await like so:

async function executeQuery () {
    try {
    const item = await query.exec()

    if (item === null || item.length === 0) {
        queryDict = { 
            status: 'empty',
            comment: 'some comment' 
        };

        console.log(`queryDict: ${queryDict}`);
        }
    }
    catch (err) {
        handleError(err);
    }
}


executeQuery()

Upvotes: 1

Related Questions