0

I have an array of objects like following

[
  {
    grade: "Grade1",
    subject: "Subject1"
  },
  {
    grade: "Grade2",
    subject: "Subject2"
  },
  .....
]

I want to check if any of the subject in the array already exists in mongodb. What is the best practice to perform this action?

Currently I am using the following code, but I think it's not good practice to use await again and again

for(var i = 0; i< grades.length; i++)
{
    var subject = await Subject.findOne({subject: grades[i].subject});

    if(subject)
    {
        return res.status({BAD_REQUEST}).json({
          hasError: true,
          message: grades[i].subject+" of "+grades[i].grade+" is already taken"
        })
    }
}

1 Answer 1

1

Fetch all the subject at once and then query only once so it will reduce the number of hits in the database and also the usage of await will be reduced.

let subjects = array.map(i => i.subject)

let subjectList = await Subject.find({ subject: { $in: subjects } });
Sign up to request clarification or add additional context in comments.

1 Comment

Great @ZainUlAbideen!

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.