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"
})
}
}
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 } });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.