亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

同時計算多個集合中的文檔數

同時計算多個集合中的文檔數

慕妹3146593 2023-07-29 16:48:18
我想同時計算三個獨立 MongoDB 集合中的文檔數量。我現在所擁有的可以工作,但速度很慢。誰能幫我優化一下嗎?app.post('/fetch-numbers',(req, res) => {  let numbers = {};  Clinic.countDocuments({})  .then(clinicCount => {    numbers.clinicCount = clinicCount;    Dentist.countDocuments({})    .then(dentistCount => {      numbers.dentistCount = dentistCount;      Booking.countDocuments({})      .then(bookingCount => {        numbers.bookingCount = bookingCount;        res.json(numbers)      })    })  })  .catch(err => {    res.json(err)  });});
查看完整描述

1 回答

?
嗶嗶one

TA貢獻1854條經驗 獲得超8個贊

由于所有查詢都是獨立的,因此您可以使用 并行運行它們promise.all(),代碼將如下所示:


app.post('/fetch-numbers', async (req, res) => {

? ? Promise.all([

? ? ? ? Clinic.countDocuments({}),

? ? ? ? Dentist.countDocuments({}),

? ? ? ? Booking.countDocuments({})

? ? ])

? ? .then((docCounts) => {

? ? ? ? const numbers = docCounts.reduce((a, b) => a + b, 0)

? ? ? ? res.json(numbers);

? ? })

? ? .catch(err => res.json(err));

? ? const numbers = docCounts.reduce((a, b) => a + b, 0)

? ? res.json(numbers);

});

async-await您可以通過使用with進一步使其更具可讀性Promise.all(),例如:


app.post('/fetch-numbers', async (req, res) => {

? ? try {

? ? ? ? const docCounts = await Promise.all([

? ? ? ? ? ? Clinic.countDocuments({}),

? ? ? ? ? ? Dentist.countDocuments({}),

? ? ? ? ? ? Booking.countDocuments({})

? ? ? ? ]);

? ? ? ? const numbers = docCounts.reduce((a, b) => a + b, 0)

? ? ? ? res.json(numbers);

? ? } catch(err) {

? ? ? ? res.json(err);

? ? }

});

查看完整回答
反對 回復 2023-07-29
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號