[英]Sequelize loop of findOne queries
我有兩個表 A 和 B。場景是我在循環上運行一個數組,以在插入表 B 之前在表 A 上的 findOne 查詢中使用這些條目。即使數組中的一個項目在表 A 中不存在操作應該失敗。 我現在擁有的如下
var idList = [1,2,3,4,5];
for (i=0; i<idList.length; i++){
await A.findOne({ where: { id : i }}).then((product) => {
if(!product){
notValidItem.push(i);
}
});
if (notValidItem.length > 0){
return res.status(400).send({ message : 'Invalid Operation' });
}
else{
next();
//going ahead with inserting into table B
}
}
上述方法肯定有效......但我們是否有更多 lamda 或 function 面向實現,而不是上述代碼中的循環? 提前感謝您的幫助。
由於我有一個優勢,即數據庫中的數組項和項將是唯一的,因此以下方法對我有用
var idList = [1,2,3,4,5];
A.findAll({ where: { id : { [Op.in] : idList }}}).then((foundItems) => {
foundItemsArray = foundItems.map((x) => x.id);
diffence = idList.filter(x => !foundItemsArray.includes(x));
if(diffence.length > 0){
//failure here
}
else{
next();
}
})
使用 Promises 的一種解決方案是使用 Promise.all()。 如果其中任何一個 Promise 失敗,你會得到一個錯誤。
try {
let idList = [1,2,3,4,5];
let promisesArray = [];
for (i=0; i<idList.length; i++){
promisesArray.push(A.findOne({ where: { id : i }}))
}
await Promise.all(promisesChangeMenuOrder);
next();
} catch (error) {
console.log(error) // don't console.log errors in production
return res.status(400).send({ message : 'Invalid Operation' });
}
下一個解決方案是:
let rows = A.findAll({
where: {
id: [1,2,3,4,5]
}
})
現在檢查長度是否應該是,如果這些值不是 null。 我認為這是更好的解決方案......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.