我目前正在制作一个电子商务应用程序,并尝试制作结帐API,该API将为多个商店提供相应的应付金额。我确信该逻辑工作正常,因为可以正确创建历史记录,但似乎API更新部分的问题是,在再次运行循环之前,它不会保存并返回更新值。以下是源代码
`
export default async function checkoutPayment(req, res) {
if (req.method == "POST") {
console.log('CONNECTING TO MONGO');
await connectMongo();
console.log('CONNECTED TO MONGO');
const { sen, amt, mass_rec, pin, massCheck_id } = JSON.parse(req.body)
const sender = await Student.findById(sen)
//to get the orders in order
const orders = await Promise.all((
massCheck_id.map(async (check_id) => {
return await CheckOutItem.findById(check_id)
})
))
// to get the stores for updating the account details
const storeStruct = []
for (let i = 0; i < orders.length; i++) {
storeStruct.push(await Seller.find({ storename: orders[i].storename }))
}
//get an ordered list of store ids
const store_id = []
for (let i = 0; i < orders.length; i++) {
store_id.push(await Seller.find({ storename: orders[i].storename }).select("_id"))
}
console.log(store_id[1])
if (pin === sender.pin) {
if (sender.account_bal > amt) {
const new_store_bal = []
let i = 0;
//gets array ordered list of new account balances
for (i = 0; i < storeStruct.length; i++) {
if (storeStruct[i][0].storename === orders[i].storename) {
new_store_bal.push(storeStruct[i][0].account_bal + orders[i].amount)
}
}
for (let i = 0; i < storeStruct.length; i++) {
console.log(storeStruct[i][0].account_bal + new_store_bal[i])
// supposed to credit the sellers accounts
const sled = await Promise.all((
store_id.map(async (id) => {
return await Seller.findById(id).updateOne({ account_bal: storeStruct[i][0].account_bal + new_store_bal[i] })
})
))
//creates history of transactions
const rec_history = await TransferHistory.create({
sender: sender.firstname + sender.lastname,
reciever: storeStruct[i][0].storename,
amount: new_store_bal[i],
trans_type: "CREDIT",
send_id: sen,
rec_id: storeStruct[i][0]._id
})
}
return res.status(200).json({ message: "successful" })
} else {
return res.status(256).json({
message: "insufficient funds",
});
}
} else {
return res.status(245).json({
message: "incorrect pin"
})
}
} else {
return res.status(400).json({
message: "wrong request",
});
}
}
`
1条答案
按热度按时间0s7z1bwu1#
UpdateOne需要filter作为第一个参数,然后需要updateValues作为第二个参数。由于您正在使用updateOne执行findById,因此将执行两个筛选器。
使用findByIdAndUpdate
添加
{new: true}
以返回更新后的文档