使用Mongoose中间件删除钩子从数组中删除级联(Cascade delete from array using Mongoose middleware remove hook)

编程入门 行业动态 更新时间:2024-10-27 08:23:51
使用Mongoose中间件删除钩子从数组中删除级联(Cascade delete from array using Mongoose middleware remove hook)

我正在使用Mongodb和mongoose构建一个Node.js表达RESTfull API。

这是我的架构:

var UserSchema = new mongo.Schema({ username: { type: String }, password: { type: String, min: 8 }, display_name: { type: String, min: 1 }, friends: { type: [String] } }); UserSchema.post('remove', function(next){ console.log({ friends: this._id }); // to test if this gets reached (it does) UserSchema.remove({ friends: this._id }); });

这是删除用户的功能:

.delete(function(req, res) { User.findById(req.params.user_id, function(err, user) { if (err) { res.status(500); res.send(err); } else { if (user != null) { user.remove(); res.json({ message: 'User successfully deleted' }); } else { res.status(403); res.json({ message: 'Could not find user.' }); res.send(); } } }); });

我需要做的是当用户被删除时,他或她的_id(字符串)也应该从所有其他用户的朋友数组中删除。 因此,架构中的删除钩子。

现在用户被删除并且钩子被触发,但用户_id没有从friends数组中删除(用Postman测试):

[ { "_id": "563155447e982194d02a4890", "username": "admin", "__v": 25, "password": "adminpass", "display_name": "admin", "friends": [ "5633d1c02a8cd82f5c7c55d4" ] }, { "_id": "5633d1c02a8cd82f5c7c55d4", "display_name": "Johnybruh", "password": "donttouchjohnsstuff", "username": "John stuff n things", "__v": 0, "friends": [] } ]

对此:

[ { "_id": "563155447e982194d02a4890", "username": "admin", "__v": 25, "password": "adminpass", "display_name": "admin", "friends": [ "5633d1c02a8cd82f5c7c55d4" ] } ]

为了试图找出它,我查看了Mongoosejs文档 ,但是mongoose doc示例并没有涵盖删除钩子。 此stackoverflow问题,但这个问题似乎是关于从其他模式中删除。

我想我正在做错误的钩子,但我似乎无法找到问题。

提前致谢!

编辑:

我无法得到cmlndz的第一个建议,所以我最终用包含待删除用户ID的数组获取所有文档并逐个从中提取:

删除功能现在包含了一些魔术代码:

// retrieve all documents that have this users' id in their friends lists User.find({ friends: user._id }, function(err, friends) { if (err) { res.json({ warning: 'References not removed' }); } else { // pull each reference to the deleted user one-by-one friends.forEach(function(friend){ friend.friends.pull(user._id); friend.save(function(err) { if (err) { res.json({ warning: 'Not all references removed' }); } }); }); } });

I am building a Node.js express RESTfull API using Mongodb and mongoose.

This is my schema:

var UserSchema = new mongo.Schema({ username: { type: String }, password: { type: String, min: 8 }, display_name: { type: String, min: 1 }, friends: { type: [String] } }); UserSchema.post('remove', function(next){ console.log({ friends: this._id }); // to test if this gets reached (it does) UserSchema.remove({ friends: this._id }); });

And this is the function that removes a User:

.delete(function(req, res) { User.findById(req.params.user_id, function(err, user) { if (err) { res.status(500); res.send(err); } else { if (user != null) { user.remove(); res.json({ message: 'User successfully deleted' }); } else { res.status(403); res.json({ message: 'Could not find user.' }); res.send(); } } }); });

What I need to do is when a user is removed, his or her _id (String) should also be removed from all the other users' friends array. Hence the remove hook in the schema.

Right now the user gets deleted and the hook gets triggered, but the user _id is not removed from the friends array (tested with Postman):

[ { "_id": "563155447e982194d02a4890", "username": "admin", "__v": 25, "password": "adminpass", "display_name": "admin", "friends": [ "5633d1c02a8cd82f5c7c55d4" ] }, { "_id": "5633d1c02a8cd82f5c7c55d4", "display_name": "Johnybruh", "password": "donttouchjohnsstuff", "username": "John stuff n things", "__v": 0, "friends": [] } ]

To this:

[ { "_id": "563155447e982194d02a4890", "username": "admin", "__v": 25, "password": "adminpass", "display_name": "admin", "friends": [ "5633d1c02a8cd82f5c7c55d4" ] } ]

To try and figure it out I have looked at the Mongoosejs Documentation, but the mongoose doc example doesn't cover the remove hook. Also this stackoverflow qestion but this question seems to be about removing from other schemas.

I think i'm doing the remove in the hook wrong, but I can't seem to find the problem.

Thanks in advance!

EDIT:

I could not get the first suggestion by cmlndz to work, so I ended up fetching all the documents with arrays that contained the to-be-deleted users' id and pulling it from them one-by-one:

The delete function now contains this bit of code that does the magic:

// retrieve all documents that have this users' id in their friends lists User.find({ friends: user._id }, function(err, friends) { if (err) { res.json({ warning: 'References not removed' }); } else { // pull each reference to the deleted user one-by-one friends.forEach(function(friend){ friend.friends.pull(user._id); friend.save(function(err) { if (err) { res.json({ warning: 'Not all references removed' }); } }); }); } });

最满意答案

您可以使用$ pull查找“friends”数组中包含“ID”的所有文档 - 或者 - 找到任何匹配的文档并逐个弹出数组中的“ID”。

You could use $pull to find all documents that contain the "ID" in the "friends" array -or- find any matching document and popping the "ID" out of the array one by one.

更多推荐

本文发布于:2023-07-20 07:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1195959.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:钩子   组中   中间件   级联   Mongoose

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!