使用Mongoose中间件从arrays级联删除钩子

我使用Mongodb和mongoose构build了一个Node.jsexpression式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 }); }); 

这是删除用户的function:

 .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(string)也应该从所有其他用户的朋友arrays中删除。 因此,架构中的删除挂钩。

现在,用户被删除,钩子被触发,但用户_id不会从朋友数组中删除(用Postmantesting):

 [ { "_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示例没有包含remove钩子。 另外这个stackoverflow问题,但这个问题似乎是从其他模式中删除。

我想我是在做错误的钩子删除,但我似乎无法find问题。

提前致谢!

编辑:

我无法通过cmlndz得到第一个build议,所以我最终获取了包含要删除的用户标识的数组的所有文档,并从中逐一提取:

现在删除function包含这一点的代码,这是神奇的:

 // 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”的所有文档 – 或者 – find任何匹配的文档,并从数组中逐个popup“ID”。