0

this is a bit of a beginners question. I need to query/find multiple elements from an array in my mongodb database. If at least one element pass an if-statement i want to set an error variable to true. Unfortunately because of the async call the variable will be returned early and remains false. Can you give me a hint on how to achieve this. Here is the code so far:

 objects = ["a","b","c"]
for (object of objects) {
    loanObject.findById(object._id)
        .then((object) => {
            if (object) {
                isError = true
            }

        })
        .catch(err => console.log(err))
}



console.log(isError) // returns false while should be true

1 Answer 1

3

use await and async, what you're currently doing is looping through your array, for each element you're firing a db call and telling it to set isError when it finishes but you're not waiting for it, so your code starts 3 db calls and then moves immediately to log isError which is false by default I guess in your code. When the db calls finish isError is being set to true but your code executed the console.log long before that.

Try this:

    for (object of objects) {
    const object = await loanObject.findById(object._id).catch(err => console.log(err));
    if (object) {
        isError = true;
    }
}

but a better solution is to use the mongoose $in operator so:

    const object = await loanObject.findOne({ _id: { $in: objects.map(object => object._id) } }).catch(err => console.log(err));
    if (object) {
      isError = true;
    }

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

Comments

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.