Home > Software engineering >  How to delete object Redis list item?
How to delete object Redis list item?

Time:06-30

I am using delete function in a scenario for cache deleting data from mongodb butenter image description here how can i delete data which is specific object from redis. I used Lrem() but it didn't work, I would appreciate it if you could help me.

const deleteComment = async (req, res) => {
  let key = `Comments/${req.query.postId}`;

  try {
    const deleteValue = await Comment.findOneAndDelete({
      _id: req.params.id,
      $or: [{ writer: req.user.id }, { authorId: req.user.id }],
    })
      .populate("responseTo", "writer")
      .populate("postId", "authorId")
      .populate("writer");

    const jsonData = JSON.stringify(deleteValue);
    await client.lRem(key, 0, jsonData);

    res
      .status(200)
      .json({ success: true, message: "Comment Deleted", ıtem: deleteValue });
  } catch (err) {
    res.status(500).json({ message: err });
  }
};

CodePudding user response:

Do you have control over the code that inserts the JSON? If so, you'll need to make sure they generate the same strings. LREM requires an exact match to work. That said, you might want to consider a different data structure or maybe a combination of data structures.

One option is that you could store the JSON as a String and then the List could contain the keys to those Strings. Then, when you delete a comment, you call LREM to remove it from the List and UNLINK or DEL to remove the JSON. The List serves to store an ordered index of the comments. The comments themselves are each stored in a String.

If you can use RedisJSON, you could just store a JSON document with an array of the comments. That would give you ordered data and the data itself and then you could delete a particular comment using JSON.DEL and JSONPath.

  • Related