I'm building social network app using nodejs and mongodb. Now in my user schema i have an array of ids of users who are following certain user and ids of users who are followed by certain user. When i delete the user i want to delete his id from all arrays inside of users who are following him. So that if he deletes his accont he is not going to be followed by any user anymore
following: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
followers: [{ type: mongoose.Schema.ObjectId, ref: "User" }],
CodePudding user response:
Mongoose middlewares are used for uses cases similar to yours, you can specify a middleware function to run before a defined operation (here we specify "remove" and the middleware runs before the operation using "pre" here is a simple implementation:
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();
});
CodePudding user response:
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,
});
});
It worked like this. I'm just interested is this the right way.