简体   繁体   English

MongoDB/Mongoose $pull 一个数组中的 Object ,其中 Object 的 _id 匹配

[英]MongoDB/Mongoose $pull an Object in an Array where _id of the Object is matching

I have this Schema here我在这里有这个架构

在此处输入图像描述

Consider the likedTours which is an Array of Objects (Tours) (ignore position 0).考虑likedTours ,它是一个对象数组(旅游)(忽略 position 0)。 I want to pull any Objects where the _id of a Tour matches the critiria.我想提取 Tour 的_id与标准匹配的任何对象。

Adding a new Tour upon liking a tour is okay, but on unlike I don't know how to pull that item out.喜欢旅游时添加新的旅游是可以的,但不像我不知道如何把那个项目拉出来。

Here is my function in the Controller in the Node.JS backend这是我在 Node.JS 后端的 Controller 中的 function

const unlikeTour = async (req, res) => {
   try {
      TourDB.Tour.findOneAndUpdate(
         { _id: req.params.tourid },
         {
            $pull: { likedUsers: req.userID },
            $inc: { likes: -1 },
         }
      ).exec(async (err, docs) => {
         if (!err) {
            try {
               await UserDB.User.findOneAndUpdate(
                  { _id: req.userID },
                  { $pull: { 'likedTours._id': docs._id } } //Here I need help
               ).exec()
               return res.status(200).send({ successMessage: 'Tour successfully unliked' })
            } catch (err) {
               return res.status(500).send({ errorMessage: 'User not found' })
            }
         } else {
            return res.status(500).send({ errorMessage: 'Tour not found' })
         }
      })
   } catch (err) {
      return res.status(500).send({ errorMessage: err })
   }
}

This method looks for a tour and update it by pulling out the userID and decrement the likes count by -1.此方法查找游览并通过提取用户 ID 并将喜欢计数减少 -1 来更新它。 And then I try to find in the UserDB that tour in the likedTours and tried to pull but it doesn't not work like that.然后我尝试在用户数据库中找到likedTours中的巡演并尝试拉,但它不能那样工作。

Thanks in advance提前致谢

you can update as你可以更新为

await UserDB.User.findOneAndUpdate(
  { _id: req.userID },
  { $pull: { likedTours: { _id: docs._id } } } //Here I need help
).exec();

reference:https://docs.mongodb.com/manual/reference/operator/update/pull/参考:https://docs.mongodb.com/manual/reference/operator/update/pull/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM