【问题标题】:Delete user id from documents after deleting user删除用户后从文档中删除用户 ID
【发布时间】:2022-11-26 23:06:56
【问题描述】:

我正在使用 nodejs 和 mongodb 构建社交网络应用程序。现在在我的用户模式中,我有一组关注特定用户的用户 ID 和关注特定用户的用户 ID。当我删除用户时,我想从关注他的用户的所有数组中删除他的 ID。这样一来,如果他删除了自己的帐户,就不会再有任何用户关注他

    following: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
    followers: [{ type: mongoose.Schema.ObjectId, ref: "User" }],

【问题讨论】:

    标签: node.js mongodb mongoose schema social-networking


    【解决方案1】:

    Mongoose 中间件用于与您类似的用例,您可以指定一个中间件函数在定义的操作之前运行(这里我们指定“remove”并且中间件在使用“pre”的操作之前运行这里是一个简单的实现:

    const userSchema = new Schema(
    {
        username: {
            type: Schema.Types.String,
            required: true,
        },
        //.....
    });
    
    userSchema.pre('remove', async function (next) {
       // remove userid from all following arrays in users collection
       // reference user with "this"
       userModel.updateMany(
           {
               following: {
                   $in: [this._id]
               }
           },
           {
               $pull: {
                   following: { _id: this._id }
               }
           });
       // calling next will call next middleware which will delete user
       next();
     });
    

    【讨论】:

    • 不幸的是那没有用。但似乎从未达到过这个中间件。当我从控制台登录到控制台“删除”时,它不会出现。我正在使用 findByIdAndRemove 删除我的文档。文档已删除,但他的 ID 仍然存在于其他文档中
    【解决方案2】:
    exports.deleteUser = catchAsync(async (req, res, next) => {
      await User.findByIdAndRemove(req.params.id);
      const data = await User.updateMany(
        {
          following: {
            $in: [req.params.id],
          },
        },
        {
          $pull: {
            following: req.params.id,
          },
        }
      );
      res.status(200).json({
        status: "success",
        data,
      });
    });
    

    它是这样工作的。我只是感兴趣这是正确的方法。

    【讨论】:

      猜你喜欢
      • 2020-05-12
      • 2018-11-21
      • 2020-07-25
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多