Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

node.js - Why pull is not removing elements

I have been trying to remove elements from the array, seem like it's not working, here is the model 1. Question Model

   {

    reviews: [{ type: ObjectID, ref: 'Review' }]

   }

2. Review Model

    {
      description: {
      type: String
    },
      userId: {
      type: ObjectId,
      ref: 'User'
    }
   }

And here is my service for the Quuestion.js

export const deleteReview = async ({ reviewId, id }, user) => {
  try {
    const result = await Question.updateOne(
      { _id: id },
      {
        $pull: { reviews: { _id: reviewId, userId: user._id } }
      }
    ).exec();
    if (result.nModified === 0) {
      throw new APIError({ message: msg('Unauthorized'), status: 401 });
    }
    return result;
  } catch (error) {
    throw error;
  }
};

Routes file

  router.delete('/questions/:id/reviews/:reviewId', auth, async (req, res) => {
    try {
      const {
        params,
        user
      } = req;
      const data = await deleteReview( params,
        user);
      return res.status(200).json({ data });
    } catch (err) {
      error(res, err);
    }
  });

I was trying to remove the elements but it's not removing at all, I have no idea where I did a mistake.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the solution I got, the $pull is not working so applied the $pullAll

export const deleteReview = async ({ reviewId, id }, user) => {
  try {
    const result = await Question.updateOne(
      { _id: id },
      {
        $pullAll: { reviews: [{ _id: reviewId, userId: user._id }] }
      }
    ).exec();
    if (result.nModified === 0) {
      throw new APIError({ message: msg('Unauthorized'), status: 401 });
    }
    return result;
  } catch (error) {
    throw error;
  }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...