0

I am working on a side project, trying to up my knowledge of React.js and Node.js and I have the following code in my Node server:

export const deleteConnection = async (req, res) => {
  try {
    let deletedConnection = await Connection.findByIdAndDelete(
      req.params.connectionId
    ).exec();
    let user = await User.findById(req.params.userId).exec();
    console.log(user);
    const remainingConnections = user.connections.filter(
      (c) => c.connection !== req.params.connectionId
    );
    console.log(remainingConnections);
    res.status(200).json(deletedConnection);
  } catch (err) {
    console.log(err);
    res.status(400).send("Unable to delete connection", err);
  }
};

In the code, I have a collection called Connection and another one called User. I delete the Connection collection, and then I'm trying to filter out the Connection that matches the connectionId. However, it isn't working, and I don't know why. There are no errors in the code, and I leave screenshots below of what the server prints out. The Connection collection is deleted, but the filter is not filtering out the Connection that matches the connectionId, so I have no way of updating the User collection. I don't know if I'm missing something about Node.js that prevents it from working, but in React.js something like this would definitely work.

For reference, the userId is the string ending with bb8bd83 and the connectionId is ending with bb8bd8f. The top object in the second screenshot is the Connection that matches the connectionId (which shouldn't appear), and everything is accessed correctly (e.g. nothing prints out undefined or anything like that). Below is what the user console.log prints out:

enter image description here

And here is what the remainingConnections console.log prints out: enter image description here

src2012
  • 89
  • 6
  • 3
    [Please post text, not images.](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question/285557#285557) – Dave Newton Jan 12 '23 at 16:54
  • Why are some of the ids printed white bare hex and some are green single-quoted strings? Are you comparing an ObjectID object (or something similar) to a string with !==? (See [Comparing mongoose _id and strings](https://stackoverflow.com/q/11637353/1563833)) – Wyck Jan 12 '23 at 17:02
  • @Wyck that was the issue thanks so much! – src2012 Jan 12 '23 at 17:09

0 Answers0