[英]Adding properties to an object from MongoDB in an array and sending it in the response
我正在嘗試使用以下代碼在users
數組的元素(在本例中為對象)中添加quoteValue
鍵值。
當我打印出console.log(users[0])
,它沒有顯示users[0]
的quoteValue
值。 但是, console.log(users[0].quoteValue)
打印的是quoteValue
的實際值。
我不明白這怎么可能。 非常感謝您的幫助!
export async function get_client_users(req, res) { try { let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 }); for(let i = 0; i < users.length; i += 1) { let quotes = await Quote.find({client: users[i]._id}); const totalQuote = quotes.length; let cost = 0; for(let i = 0; i < quotes.length; i += 1) { cost += quotes[i].total_cost; } const result = { totalQuote: totalQuote, quoteValue: cost } Object.assign(users[i], result); } return res.status(200).json(users); } catch(e) { console.log(e); return res.status(400).json({ message: 'Technical Error. Please try again later.' }); }; };
如果可以創建一個新的users
對象(在下面的代碼中稱為updatedUsers
),我會建議使用析構( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment )所以:
export async function get_client_users(req, res) {
try {
let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 });
let updatedUsers = [];
for(let i = 0; i < users.length; i++) {
let quotes = await Quote.find({client: users[i]._id});
let quoteValue = 0;
for(let i = 0; i < quotes.length; i++) {
quoteValue += quotes[i].total_cost;
}
updatedUser = {
...users[i],
totalQuote: quotes.length,
quoteValue
}
updatedUsers.push(updatedUser);
}
return res.status(200).json(updatedUsers);
} catch(e) {
console.log(e);
return res.status(500).json({ message: 'An error occurred. Please try again later.' });
};
};
我還進行了一些修改,例如發送500
,而不是400
時發生錯誤,除去分配給totalQuote
通過分配可變quotes.length
直接updatedUser.totalQuote
,並且還使用i++
代替i += 1
在for
循環。 我會建議棉絨如ESLint(的使用https://eslint.org/ )或更漂亮( https://prettier.io/ ),以提高代碼的可讀性。
此外,我建議使用map
( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map )迭代您的users
對象並reduce
( https:// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce )從您的quotes
的total_cost
屬性中獲取quoteValue
的值,但這超出了您的問題范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.