我正在使用nodejs和mongodb构建社交网络应用程序。现在,在我的用户模式中,我有一个跟踪特定用户的用户ids数组和一个由特定用户跟踪的用户ids。当我删除用户时,我想从跟踪他的用户内部的所有数组中删除他的id。因此,如果他删除他的授权,他将不再被任何用户跟踪。
following: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
followers: [{ type: mongoose.Schema.ObjectId, ref: "User" }],发布于 2022-11-26 13:22:38
猫鼬中间件用于类似于您的使用情况,您可以指定要在定义的操作之前运行的中间件函数(在这里,我们指定"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"
await userModel.updateMany(
{
following: {
$in: [this._id]
}
},
{
$pull: {
following: { _id: this._id }
}
});
// calling next will call next middleware which will delete user
next();
});发布于 2022-11-26 14:52:13
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,
});
});它是这样工作的。我只是感兴趣的是这是正确的方式。
https://stackoverflow.com/questions/74582418
复制相似问题