是什么导致 Mongoose updateMany 返回 {acknowledged: false }`

Der*_*Kim 7 mongoose mongodb node.js express

我正在尝试使用 MongoDB 为 Express 应用程序设置通知。

我有一个 API 端点,我将$push用户的 id 添加到readByMongoDB 中的字段,以在检索用户的通知后将其“标记”为已读。当我向此端点发出请求时,它会返回200其通知,但不会对 MongoDB 中的通知文档进行任何更新。console.log在回调中查询响应给了我{ acknowledged: false }。根据Mongoose 文档acknowledged是 a Boolean indicating everything went smoothly,但是有关acknowledged查询/写入过程中是什么以及在哪一点导致它发生的信息很少。由于它没有返回任何错误,我找不到解决问题的方法。

有人能够阐明它到底acknowledged: false是什么以及通常导致它的原因,以及为什么它不会抛出错误。

模型:

const notificationSchema = new Schema({
  timestamp: {
    type: Date,
    required: true
  },
  type: {
    type: String,
    required: true,
    enum: [
      'newCustomer',
      'contractSigned',
      'invoicePaid',
      'warrantyExp',
      'assignedProject'
    ]
  },
  recipients: [{
    type: Schema.Types.ObjectId,
    ref: 'Employee',
    required: true,
  }],
  customer: {
    type: Schema.Types.ObjectId,
    ref: 'Customer',
    required: true,
  },
  readBy: [{
    type: String
  }],
  uuid: {
    type: String,
    default: uuid.v4,
    immutable: true,
    required: true,
  },
  company: {
    type: Schema.Types.ObjectId, ref: 'Company'
  }
});
Run Code Online (Sandbox Code Playgroud)

路线:

router.get("/notification/all", withAuth, async (req, res) => {
  const FOURTEEN_DAYS = new Date().setDate(new Date().getDate() + 14);
  try {
    const { uuid, userId } = req.loggedInUser;

    // Fetch notifications that have the user as a recipient.
    Notification.find({
      recipients: userId,
    })
      .populate("customer")
      .exec((err, notifs) => {
        if (err)
          return res.status(500).json({
            success: false,
            message: "Error: Failed to retrieve notifications.",
          });

        const result = [];
        const notifIds = [];

        for (const notif of notifs) {
          // Filter notif
          result.push({
            timestamp: notif.timestamp,
            customer: notif.customer,
            type: notif.type,
            read: notif.readBy.includes(uuid),
          });
          // Add the user as read
          notifIds.push(notif.uuid);
        }

        console.log(notifIds);

        /* THIS RETURNS ACKNOWLEDGED: FALSE */         
        // Write to DB that user has read these notifications
        Notification.updateMany(
          { uuid: { $in: notifIds } },
          { $push: { readBy: uuid } },
          (err, resultUpdate) => {
            if (err)
              return res.status(500).json({
                success: false,
                message:
                  "Error: Failed to add check off notifications as read.",
              });

            console.log(resultUpdate);

            // Delete notifications past 14 days and has been read by all recipients
            Notification.deleteMany(
              {
                timestamp: { $gte: FOURTEEN_DAYS },
                $expr: {
                  $eq: [{ $size: "$readBy" }, { $size: "$recipients" }],
                },
              },
              (err) => {
                if (err)
                  return res.status(500).json({
                    success: false,
                    message: "Error: Failed to delete old notifications.",
                  });

                return res.status(200).json({
                  success: true,
                  notifications: result,
                  message: "Fetched notifications",
                });
              }
            );
          }
        );
      });
  } catch (err) {
    res.status(500).json({ success: false, message: err.toString() });
  }
});
Run Code Online (Sandbox Code Playgroud)

Der*_*Kim 17

所以事实证明这个问题与写入关注无关。acknowledged: false被返回是因为我们想要的值$pushundefined. 因此,本质上 Mongoose 拒绝写入undefined值,但不会因输入值未定义而抛出错误。将其放在这里以防其他人遇到此问题。