【问题标题】:Find ObjectId of an element inside an array of docs, that is inside a model with Mongoose查找文档数组中元素的 ObjectId,该元素位于带有 Mongoose 的模型中
【发布时间】:2021-05-27 15:46:10
【问题描述】:

我有这个模型:

const userSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    },
    firstname: String,
    lastname: String,
    password: {
        type: String,
        required: true
    },
    activities: [{
        description: {
            type: String,
            required: true
        },
        status: String,
        from: Date,
        to: Date
    }]
}, { timestamps: true })

在获得User.findById() 的用户后,如何获得activities 数组中活动的ObjectId,以便执行(例如)deleteupdate 操作?

编辑 1 我可以使用 console.log() 或在我的 GUI 中查看每个 ObjectId,因为即使我没有为每个元素指定字段 _id,MongoDB 也会为数组中的每个元素创建一个 ObjectId。这是一个示例:

USER ACTIVITIES [
  {
    _id: 603765c7bb1d1c24cc7f80ff,
    description: 'Complete the project',
    status: 'pending',
    from: 2021-02-25T08:54:31.719Z,
    to: 2021-02-25T08:54:31.719Z
  },
  {
    _id: 60377672bb1d1c24cc7f8100,
    description: 'Figure out how to get the ObjectId',
    status: 'pending',
    from: 2021-02-25T10:05:38.144Z,
    to: 2021-02-25T10:05:38.144Z
  }
]

我想访问这个_id,以便对单个活动执行操作

【问题讨论】:

    标签: node.js arrays mongodb mongoose mongoose-schema


    【解决方案1】:

    我刚刚找到了解决方案。在我的路由文件中,我在端点路径(元素 ID)中又添加了一个参数,因此我可以通过 req.params 访问它。然后一切都很简单。这是一个示例:

    路线

    router.delete('/activities/:id/:activityId', userController.deleteActivity);
    

    逻辑

    exports.deleteActivity = async (req, res, next) => {
      try {
        const id = req.params.id;
        const user = await User.findById(id);
        if (user) {
          const activityId = req.params.activityId;
          await user.activities.pull(activityId);
          await user.save();
          console.log("ACTIVITY REMOVED! YOUR ACTIVITIES", user.activities);
          return res.status(200).json({ activities: user.activities });
        }
        return res.status(400).json({ message: "USER NOT FOUND!" });
      } catch (error) {
        console.log(error);
        res.status(500).json({ error });
      }
    };
    
    

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2018-06-17
      • 2016-04-14
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 2014-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多