簡體   English   中英

MongoDB 和 Mongoose - 來自兩個不同集合查詢的 ID 不匹配

[英]MongoDB and Mongoose - id from two different collection queries not matching

我正在構建一個應用程序,人們可以在其中制作便餐並邀請其他用戶參加他們的便餐。 我有一個似乎很簡單的問題,但我無法讓它工作:

我想創建一個邀請路線來檢查 potluck.attendees 以查看他們之前是否被邀請過(並根據他們是 0-pending、1-attending還是重新邀請他們,如果他們之前被邀請過,發送不同的錯誤)並且他們的狀態為 2 拒絕),如果不是,則將受邀者放入 potluck.attendees 對象數組中,並將potluck 的 _id 放入受邀者的 user.potluks 對象數組中。

以下是這兩個模型的超級修剪版本:

簡化的聚餐模式

const PotluckSchema = new Schema({
  attendees: [
    {
      attendeeId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
      },
      status: Number,
      enums: [
        0, //'pending',
        1, //'attending',
        2 //'declined'
      ]
    }
  ]
});

簡化的用戶模型

const UserSchema = new Schema({
  potlucks: [
    {
      potluck: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Potluck'
      }
    }
  ]
});

到目前為止,我在這條路線上所擁有的是:

router.put('/attendees/invite/:potluckId/:inviteeId', async (req, res) => {
  try {
    const currPotluck = await db.Potluck.findOne({
      _id: req.params.potluckId,
      createdBy: req.user._id
    });
    // Makes sure potluck belongs to user before allowing to invite
    if (!currPotluck)
      return res.status(401).json({
        msg: 'You are not authorized to invite people to this potluck.'
      });
    const invitee = await db.User.findOne({ _id: req.params.inviteeId });

    console.log(currPotluck);
    console.log(invitee);

    for (let i = 0; i < currPotluck.attendees.length; i++) {
      //  Checks if invitee already exists in potluck.attendees
      //  and if their status is 0 or 1 (pending or attending)
      //  It will stop function
      if (
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 0 ||
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 1
      ) {
        return res.status(401).send({
          error: 'This member has already been invited to your potluck'
        });
      } else if (
        currPotluck.attendees[i].attendeeId == invitee._id &&
        currPotluck.attendees[i].status == 2
      ) {
        //  if their status is 2 (declined)
        //  it will edit their existing object in the attendees array to pending
        //  and re-insert potluck in invitee's user.potlucks model
        await db.Potluck.findOneAndUpdate(
          { _id: currPotluck._id },
          { $set: { 'attendees.$[el].status': 0 } },
          { arrayFilters: [{ 'el.attendeeId': invitee._id }] }
        );
        await db.User.findOneAndUpdate(
          { _id: invitee._id },
          { $push: { potlucks: { potluck: currPotluck._id } } }
        );
        res.send(`This user has been re-invited to your potluck!`);
      }
    }
    // If they don't exist already in potluck.attendees, create new object
    // in potlucks.attendees and user.potlucks for invitee
    await db.Potluck.findOneAndUpdate(
      { _id: currPotluck._id },
      { $push: { attendees: { attendeeId: invitee._id, status: 0 } } }
    );
    await db.User.findOneAndUpdate(
      { _id: invitee._id },
      { $push: { potlucks: { potluck: currPotluck._id } } }
    );
    res.send(`This user has been invited to your potluck!`);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

現在來看問題:

如果我在郵遞員中運行此代碼,它將運行在 for 循環之后的兩個“findOneAndUpdate”,無論是否匹配。 在嘗試調試時,我在 console.logged 中同時記錄了invitee._idcurrPotluck.attendees[i].attendeeId (對於我知道受邀者已經存在於數組中的測試),它們都顯示為相同的 ID。

但是,如果我嘗試使用console.log (currPootluck.attendees[i].attendeeId == invitee._id)每次都會出現false 我為兩者做了一個“類型”,它們作為對象出現,它們在 console.logs 中似乎是相同的類型 - 可能是字符串?

我知道解決方案必須非常簡單,但我無法弄清楚,任何幫助將不勝感激!

currPootluck.attendees[i].attendeeIdinvitee._id都是ObjectIds ,為了檢查它們是否相同,您必須先將其轉換為字符串。

這應該可以完成這項工作: currPootluck.attendees[i].attendeeId.toString() == invitee._id.toString()

暫無
暫無

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

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