javascript Mongoose deleteMany在pre-hook中,如何访问所有将被删除的文档?

q0qdq0h2  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(83)

我有这个代码:

postSchema.pre('deleteMany', async function (next: NextFunction) {
  try {
    console.log(this);
    return next(); // normal save
  } catch (error) {
    return next(error);
  }
});

console.log给出了queryobject。文档是否在query中的某个位置可用?

zbwhf8kr

zbwhf8kr1#

query in deletemany位于this_conditions键处,因此您可以在Post Model中这样做,例如:

postSchema.pre('deleteMany', async function (next: NextFunction) {
  try {
   let deletedData =await Post.find(this._conditions).lean()
    console.log(deletedData );
    return next(); // normal save
  } catch (error) {
    return next(error);
  }
});

let Post= mongoose.model("Post", userSchema);
module.exports = Post
ukxgm1gy

ukxgm1gy2#

this.getFilter()this.getUpdate()是访问中间件中参数的推荐方法

postSchema.pre('deleteMany', async function (next: NextFunction) {
  try {
   let deletedData =await Post.find(this.getFilter()).lean()
    console.log(deletedData );
    next(); // are you sure you want return next() and not next()?
  } catch (error) {
    next(error); // are you sure you want return next(error) and not next(error)?
  }
});

let Post= mongoose.model("Post", userSchema);
module.exports = Post

链接到有关访问中间件的Mongoose文档

相关问题