gpt4 book ai didi

node.js - 使用 Mongoose 中间件删除钩子(Hook)从数组中级联删除

转载 作者:可可西里 更新时间:2023-11-01 10:26:30 26 4
gpt4 key购买 nike

我正在使用 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) 也应该从所有其他用户的 friend 数组中删除。因此,架构中的删除 Hook 。

现在用户被删除并且钩子(Hook)被触发,但是用户 _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 Documentation ,但 mongoose 文档示例并未涵盖删除 Hook 。还有 this stackoverflow qestion但这个问题似乎是关于从其他模式中删除的。

我认为我在钩子(Hook)中删除错误,但我似乎找不到问题。

提前致谢!

编辑:

我无法通过 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' });
}
});
});
}
});

最佳答案

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

关于node.js - 使用 Mongoose 中间件删除钩子(Hook)从数组中级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33444584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com