[英]NodeJS + MySql nested queries
我正在嘗試從數據庫中獲取用戶,然后循環遍歷每個用戶並獲取他們的圖像。 但是,當我嘗試將圖像數組分配給 user.images 屬性時,什么也沒有發生。 我仍然只得到具有空圖像數組的用戶。
目前我的代碼如下:
user.getAll().then(result =>{
const userCollection = result[0];
for(let i=0; i < userCollection.length; i++){
userCollection[i].images = [{}];
image.getImagesByUserId(userCollection[i].Id).then(res =>{
userCollection[i].images = res[0];
}).catch(err =>{
console.log(err);
res.status(400).json(err);
})
}
res.json(userCollection);
})
.catch(err =>{
console.log(err);
res.status(400).json(err);
});
為什么我不能將圖像數組分配給它的屬性?
可能是一個愚蠢的問題,但你在分配它嗎? 我只看到
userCollection[i].images = [{}];
上面,永遠看不到:
userCollection[i].images = res;
一旦你抓住圖像分配。
在我看來,您需要從回調內部運行 res.json(userCollection)。
這當然意味着您需要在回調中重命名 res 變量
這是假設您以某種方式使用 res.json(userCollection) 導出信息。 我是根據我在任何地方都沒有看到 res 定義的事實來推斷的
問題是getImagesByUserId()
是異步的,所以當您完成分配時,您已經發送了響應。
您當前的事件順序是:
res.json()
)簡單的解決方法是查看Promise.all()並在結果全部返回時匯總結果。
但是,這不是處理 SQL 數據庫的最有效方法,我建議您重新構建查詢,以便在 1 次訪問數據庫中獲取所有用戶的所有圖像,然后根據這些結果格式化響應。
假設您有一個圖像表和一個用戶表,例如:
SELECT image_name, user_id
FROM image
然后將您的 js 中的循環替換為:
getImagesForUsers().then(result => {
//create your response from the rows
res.json(response);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.