1

It's along explanation so to make it easier I'll call users x and y.

I got this code, which the intention is to the X (making the requests) add his ID into Y's pending requests as well as his own sent requests.

const postSendBBRequest = async (req, res) => {
  const userRecipient = await User.findById(req.params.id)
    const userSender = await User.findById(req.userId);
  const senderId = userSender.id;
  try {
    if (senderId == userRecipient.id) {
      res.status(406).json("You cannot have yourself as a brother")
    } else {

        userSender.sentBBRequests.push({senderId});
        await userSender.save();
            
        userRecipient.receivedBBRequests.push({senderId});
        await userRecipient.save();

        res.status(201).json("Brotheband request sent sucessfully")
      }
    } catch (ERR) {
        res.status(500).json({ Message: ERR.message });
    }
}

My test route on Postman is /add/61b29bb33e775393ae369b79

The problem is: I'm getting an error: "Cast to ObjectId failed for value \"{ senderId: '61b29aef3e775393ae369b74' }\" (type Object) at path \"sentBBRequests\

I thought maybe the problem was how I organized my Schema too:

 receivedBBRequests: [
    {
      type: mongoose.Schema.Types.ObjectId,
    },
  ],

  sentBBRequests: [
    {
      type: mongoose.Schema.Types.ObjectId,
    },
  ],

 brothers: {
    type: [
      {
        type: mongoose.Schema.Types.ObjectId,
      },
    ]}

There are too many points of failure I can't even come up with something to solve.

Thanks a lot.

  • I think the problem is that you are comparing a string `senderId` with `userSender.id` which is an ObjectId, which is a type. This should help: https://stackoverflow.com/questions/11637353/comparing-mongoose-id-and-strings – Mush-A Dec 10 '21 at 01:37

1 Answers1

0

You can use the following :

const senderId = userSender._id.toString();
const userRecipientId = userRecipient._id.toString();

this will allow you to convert the objectId to string

jugurtha moad
  • 304
  • 3
  • 5