javascript - 如何删除 Mongoose 中带有引用集合的集合?

标签 javascript node.js mongodb express mongoose

我有这个用户模型 其中以博客模型为引用,博客以评论集合为引用

const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
      index: {
        unique: true
      }
    },
    password: {
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    website: {
      type: String
    },
    bio: {
      type: String
    }
  },
  {
    timestamps: {
      createdAt: "created_at",
      updatedAt: "updated_at"
    }
  }
);

userSchema.virtual("blogs", {
  ref: "blogs",
  localField: "_id",
  foreignField: "author"
});

我也想删除博客数据以及博客集合中的任何嵌套集合 我怎样才能删除它?

最佳答案

如果我的理解正确,这会有帮助。

function deleteUserById(id){
    UserModel.findById(id, async (err, user) => {
        try{
            await deleteBlodById(user.blog._id);
            UserModel.findByIdAndRemove(id)
        }catch(e){
            throw e;
        }
    })
}
function deleteBlogById(id){
    BlogModel.findById(id, async (err, blog) => {
        // ... The pretty same thing like before, just delete 
    })
}

我希望这会有所帮助。如果您的问题类似于是否有任何函数可以自动删除文档及其所有引用的文档,我找不到类似的内容。

关于javascript - 如何删除 Mongoose 中带有引用集合的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338590/

相关文章:

javascript - 使用 jquery 或 javascript 重新加载页面时如何将文本保存在文本区域中

javascript - 变量声明的 Mac 终端 Node REPL 输出

java - 使用Java将Excel数据导入Mongodb

javascript - AngularJS:仅在一段时间过后才在ajax请求上显示加载微调器

javascript - 溢出-x :hidden; can still scroll when open at my phone

javascript - JQuery 使用全局变量链接标题

node.js - 如何在没有nodejs msi的情况下安装node js

node.js - 使用 Mocha 测试 locomotive.js

javascript - Express.js 请求主体 __proto__

javascript - mongodb find() 在node.js中返回空结果