skip to Main Content
 module.exports.follow = async (req, res) => {
    if (
      !ObjectID.isValid(req.params.id) ||
      !ObjectID.isValid(req.body.idToFollow)
    )
      return res.status(400).send("ID unknown : " + req.params.id);
  
    try {
      // add to the follower list
      await UserModel.findOneAndUpdate(
        req.params.id,
        { $addToSet: { following: req.body.idToFollow } },
        { new: true, upsert: true }
          .then((data) => res.send(data))
          .catch((err) => res.status(500).send({ message: err }))),

        // add to following list
        await UserModel.findOneAndUpdate(
          req.body.idToFollow,
          { $addToSet: { followers: req.params.id } },
          { new: true, upsert: true }
            .then((data) => res.send(data))
            .catch((err) => res.status(500).send({ message: err })))
    } catch (err) {
      return res.status(500).json({ message: err });
    }
  };
  
  module.exports.unfollow = async (req, res) => {
    if (
      !ObjectID.isValid(req.params.id) ||
      !ObjectID.isValid(req.body.idToUnfollow)
    )
      return res.status(400).send("ID unknown : " + req.params.id);
  
    try {
      await userModel.findOneAndUpdate(
        req.params.id,
        { $pull: { following: req.body.idToUnfollow } },
        { new: true, upsert: true }
          .then((data) => res.send(data))
          .catch((err) => res.status(500).send({ message: err }))),
  
        // Retirer de la liste des followers
        await userModel.findOneAndUpdate(
          req.body.idToUnfollow,
          { $pull: { followers: req.params.id } },
          { new: true, upsert: true }
            .then((data) => res.send(data))
            .catch((err) => res.status(500).send({ message: err })))
    } catch (err) {
      return res.status(500).json({ message: err });
    }
  }

I code with nodejs and I use mongoDB
in order to design a social network and I am faced with a problem… Indeed at the level of my controllers I edited a controller for the follow and unfollow between users the purpose being to retrieve and verify the identifiers two users (one who wants to subscribe to a user and the other one with whom the first subscribes). who wants to subscribe sees his table "following" recover the identifier of his host and at the latter it is the table "followers" that recovers the identifier of his subscriber. To do so I did in try-catch but when I make my request on postman (request of type patch) I am always returned to catch (err){. . . }. It follows that I do not understand what is happening and I ask for your expertise thank you in advance

I tried to change FindOneAndUpdate by FindByIdAndUpdate visibly that was not the problem

3

Answers


  1. Chosen as BEST ANSWER

    already done except that I have a second problem with my unfollow controller. On postman when I launch the request it is mentioned to me that the identifiers I entered are not recognized in other term the condition of my if is taken into account I do not understand the reason the code is higher

     module.exports.follow = async (req, res) => {
    if (
      !ObjectID.isValid(req.params.id) ||
      !ObjectID.isValid(req.body.idToFollow)
    )
      return res.status(400).send("ID unknown : " + req.params.id);
    
    try {
      // add to the follower list
         const dataOne = await UserModel.findByIdAndUpdate(
          req.params.id,
          { $addToSet: { following: req.body.idToFollow } },
          { new: true, upsert: true }
      );
      //add to the following list
            const dataTwo = await UserModel.findByIdAndUpdate(
                  req.body.idToFollow,
                  { $addToSet: { followers: req.params.id } },
                  { new: true, upsert: true }
            )
            res.status(201).json({
              dataOne : dataOne,
              dataTwo : dataTwo,
            });
    } catch (err) {
      return res.status(500).json({ message: err });
    }
    

    };

      module.exports.unfollow = async (req, res) => {
    
        if (
          !ObjectID.isValid(req.params.id) ||
          !ObjectID.isValid(req.body.idToUnfollow)
        )
          //postman's answer
          return res.status(400).send("ID unknown : " + req.params.id);
      
        try {
    
    //delete from the following list
             const dataOne = await UserModel.findByIdAndUpdate(
              req.params.id,
              { $pull: { following: req.body.idToUnFollow } },
              { new: true, upsert: true }
          );
          //delete from the followers list
                const dataTwo = await UserModel.findByIdAndUpdate(
                      req.body.idToFollow,
                      { $pull: { followers: req.params.id } },
                      { new: true, upsert: true }
                )
                res.status(201).json({
                  dataOne : dataOne,
                  dataTwo : dataTwo,
                }); 
    
        } catch (err) {
          return res.status(500).json({ message: err });
        }
      };
    

  2. The reason your code is being caught in the catch(err) block is because you have syntax issues in the try block.

    When using async/await syntax pattern you don’t need to use .then() or .catch() functions to handle the settled promises, the await keyword can handle that for you if you assign the returned value from the promise into a variable. To add to the confusion, your code is chaining the then() to one of the option objects instead of the findOneAndUpdate function.

    Change this:

    await UserModel.findOneAndUpdate(
        req.params.id,
        { $addToSet: { following: req.body.idToFollow } },
        { new: true, upsert: true } // << You are chaining then to here. This is wrong.
          .then((data) => res.send(data))
          .catch((err) => res.status(500).send({ message: err })))
    
    await UserModel.findOneAndUpdate(
          req.body.idToFollow,
          { $addToSet: { followers: req.params.id } },
          { new: true, upsert: true } // << You are chaining then to here. This is wrong.
            .then((data) => res.send(data))
            .catch((err) => res.status(500).send({ message: err })))
    

    to this:

    const dataOne = await UserModel.findByIdAndUpdate(
        req.params.id,
        { $addToSet: { following: req.body.idToFollow } },
        { new: true, upsert: true }
    );
    
    const dataTwo = await UserModel.findByIdAndUpdate(
          req.body.idToFollow,
          { $addToSet: { followers: req.params.id } },
          { new: true, upsert: true }
    )
    res.status(201).json({
       dataOne : dataOne,
       dataTwo : dataTwo,
    });
    

    I have kept the response using res.status(201).json until after both of your updates have settled. You were using res.send(data)) in the first update so the second update would never have taken place as Express will have stopped execution and returned a response.

    You would probably want to handle each one of these updates in their own try{}catch(err){} blocks because if the first one failed you want to let the user know straight away and return a response. That way the second update doesn’t get executed but I’ll leave that up to you.

    Login or Signup to reply.
  3. You have a typo in your if statement.

    You need to use ObjectId.isValid() instead of ObjectID.isValid(). Note you are using uppercase ‘ID’ when it should be ‘Id’.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search