【发布时间】:2016-01-31 09:16:26
【问题描述】:
我正在使用 Mongodb 和 mongoose 构建一个 Node.js express 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 (String) 也应该从所有其他用户的朋友数组中删除。因此,架构中的删除挂钩。
现在用户被删除并且钩子被触发,但是用户_id没有从朋友数组中删除(用邮递员测试):
[
{
"_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 Documentation,但猫鼬文档示例并未涵盖删除钩子。还有this stackoverflow qestion,但这个问题似乎是关于从其他模式中删除。
我认为我在钩子中的删除操作错误,但我似乎找不到问题。
提前致谢!
编辑:
我无法让cmlndz 的第一个建议起作用,所以我最终获取了包含要删除的用户 id 的数组的所有文档,并一个接一个地从中提取:
delete 函数现在包含以下代码:
// 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' });
}
});
});
}
});
【问题讨论】:
标签: node.js mongodb express mongoose