【问题标题】:MongoDB and Mongoose - id from two different collection queries not matchingMongoDB和Mongoose - 来自两个不同集合查询的ID不匹配
【发布时间】:2020-05-31 05:30:40
【问题描述】:

我正在构建一个应用程序,人们可以在其中制作聚餐并邀请其他用户参加他们的聚餐。我有一个看似简单的问题,但我无法让它工作:

我想创建一个邀请路由来检查 potluck.attendees 以查看他们之前是否被邀请过(并根据他们是 0-pending、1-attending 还是 发送不同的错误如果他们之前被邀请过并且他们的状态为 2 denied,则重新邀请他们),如果没有,则将被邀请者放入 potluck.attendees 对象数组中,将 potluck 的 _id 放入被邀请者的 user.potlucks 对象数组中。

以下是这两个模型的超级修剪版本:

简化的家常便饭模型

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 中看起来都是相同的类型 - 可能是字符串?

我知道解决方案必须非常简单,但我无法弄清楚,任何帮助将不胜感激!

【问题讨论】:

  • 看看here
  • 谢谢!我不知道如何正确表达这个问题,因为我一直在寻找答案:)

标签: javascript mongodb express mongoose collections


【解决方案1】:

currPootluck.attendees[i].attendeeIdinvitee._id都是ObjectIds,为了检查它们是否相同,必须先将其转换为字符串。

这应该可以完成工作:currPootluck.attendees[i].attendeeId.toString() == invitee._id.toString()

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2020-04-25
    相关资源
    最近更新 更多