首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除用户后从文档中删除用户id

删除用户后从文档中删除用户id
EN

Stack Overflow用户
提问于 2022-11-26 13:05:35
回答 2查看 31关注 0票数 0

我正在使用nodejs和mongodb构建社交网络应用程序。现在,在我的用户模式中,我有一个跟踪特定用户的用户ids数组和一个由特定用户跟踪的用户ids。当我删除用户时,我想从跟踪他的用户内部的所有数组中删除他的id。因此,如果他删除他的授权,他将不再被任何用户跟踪。

代码语言:javascript
复制
    following: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
    followers: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
EN

回答 2

Stack Overflow用户

发布于 2022-11-26 13:22:38

猫鼬中间件用于类似于您的使用情况,您可以指定要在定义的操作之前运行的中间件函数(在这里,我们指定"remove“,而中间件在使用"pre”操作之前运行,这里是一个简单的实现:

代码语言:javascript
复制
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"
   await userModel.updateMany(
       {
           following: {
               $in: [this._id]
           }
       },
       {
           $pull: {
               following: { _id: this._id }
           }
       });
   // calling next will call next middleware which will delete user
   next();
 });
票数 0
EN

Stack Overflow用户

发布于 2022-11-26 14:52:13

代码语言:javascript
复制
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,
  });
});

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74582418

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档