簡體   English   中英

貓鼬.find()在沒有匹配結果的情況下返回200響應和空數組

[英]Mongoose .find() returning 200 response and empty array when there is no matching results

我試圖通過在發送響應之前檢查查詢是否返回了某些內容來為查詢添加一層驗證。 我的問題是,當我用Postman進行測試時,即使我的收藏集中根本沒有記錄,我也會收到200響應並返回一個空數組。

router.get(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const errors = {};
    Appointment.find({ user: req.user.id })
      .populate("user", ["firstName", "lastName", "email", "phone"])
      .then(appointments => {
        if (!appointments) {
          // if the user id is not there, or if the appointments array is empty
          errors.noappointments = "You do not have any appointments booked";
          return res.status(404).json(errors);
        }
        res.json(appointments);
      })
      .catch(err => res.status(404).json(err));
  }
);

看來您期待一個real承諾。 exec給您

router.get(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const errors = {};
    Appointment.find({ user: req.user.id })
      .populate("user", ["firstName", "lastName", "email", "phone"])
      .exec()
      .then(appointments => {
        if (!appointments.length) {
          // if the user id is not there, or if the appointments array is empty
          errors.noappointments = "You do not have any appointments booked";
          return res.status(404).json(errors);
        }
        res.json(appointments);
      })
      .catch(err => res.status(404).json(err));
  }
);

看看這是否行得通。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM