Simply, I am working on a project and I faced a case and want to know if I am implementing it correctly.
I expect the client to send an array of IDs, and I need to check if each value in the array exists or not in the database. If any value does not exist, I will send a response with an error. Otherwise, I will proceed with the next actions.
I have implemented the idea in the following way:
let result = null;
for (let i = 0; i < listIds.length; i++) {
const existCheck = await branchModel.exists({ _id: listIds[i] }) != null ? true : false;
if (existCheck == false) {
result = false;
}
}
if (result != false) {
result = true;
}
return result;
}
However, I think this approach may impact performance if the array is very long, and I am not sure if calling the database multiple times in the same API is healthy and not expensive.
Is there a method in Mongoose to achieve the same idea?
Soluation :
let result = false;
let unique = [...new Set(listIds)];
const branches = await branchModel.find().where('_id').in(unique);
if(branches.length === unique.length){
result = true;
}
else{
result = false;
}
return result;
Thanks aneroid & jQueeny
Via Active questions tagged javascript - Stack Overflow https://ift.tt/cZeDvX4
Comments
Post a Comment