[英]Node.js Sequalize using create function in a loop on multiple models
[英]Node.js Sequalize creating new rows in forEach loop
我正在嘗試使用 Sequalize ORM 在數據庫中創建新行。 我從 req.query.collections 收到一組req.query.collections
。 對於每個 collections 我需要創建一個新的userCollection
。 如果沒有創建userCollection
,我想以內部服務器錯誤(第 41 行)進行響應,否則返回一個包含新創建的userCollections
的對象數組。
問題是,當我從 Postman 發出測試請求時,我不斷收到內部服務器錯誤。 當我檢查我的數據庫時,我看到這些userCollections
已創建,因此沒有發生錯誤。
我知道為什么會這樣:因為userCollection.build({ stuff }).save()
返回 promise。 因此,當我嘗試從 .then .then()
語句中 console.log userCollections
時,我得到一個包含新創建的 collections 的數組,就像我應該做的那樣。 但是到那時服務器已經響應內部服務器錯誤。
這是我的 function 代碼:
exports.addCollections = async (req, res, next) => {
const libraryId = req.params.libraryId;
const collections = req.query.collections;
if (!collections)
next(Boom.forbidden());
const userCollections = [];
collections.forEach(async (collectionId, index) => {
const collection = await Collection.findByPk(collectionId);
if (!collection)
return next(Boom.notFound());
userCollection.build({
user_id: req.user.id,
library_id: libraryId,
public_collection_id: collection.id,
title: collection.title,
description: collection.description
})
.save()
.then(newUserCollection => {
userCollections.push(newUserCollection.get({ plain: true }));
// should be printed first, but comes second
// prints out the array with newly created record
console.log(userCollections);
})
.catch(error => {
console.log(error);
});
});
// should be printed second, but comes first
// prints out empty array
console.log(userCollections);
if (userCollections.length === 0) {
next(Boom.internal());
}
res.json(userCollections);
}
發布解決方案
感謝創建本教程的塞巴斯蒂安肖邦: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404
所以我添加了這個 function:
const asyncForEach = async (array, callback) => {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
而不是collections.forEach...(blah blah)
(問題中發布的代碼的第 10 行)我這樣做:
try {
await asyncForEach(collections, async (collectionId, index) => {
const collection = await Collection.findByPk(collectionId);
if (!collection)
return next(Boom.notFound());
userCollection.build({
user_id: req.user.id,
library_id: libraryId,
public_collection_id: collection.id,
title: collection.title,
description: collection.description
})
.save()
.then(newUserCollection => {
userCollections.push(newUserCollection.get({ plain: true }));
console.log(userCollections);
})
.catch(error => {
console.log(error);
});
})
} catch (err) {
return next(Boom.internal(err.message));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.