node.js - 如何从用户集合中删除孤立的 objectid 引用?
问题描述
查找用户的控制器功能:
router.get("/:id", usersController.getUser)
getUser: async (req, res, next) => {
try {
const user = await User.findById(req.params.id)
if (!user) {
return res.status(404).json({ message: "User not found" })
}
return res.status(200).json({ user })
} catch (error) {
return next(error)
}
}
我得到了这样的回应:
{
"user": [
{
"posts": [
"5e857785591a6c1047341c60",
"5e85779f591a6c1047341c61"
],
"_id": "5e84e15ef2ae067df522c164",
"username": "rick",
"email": "rickk3@gmail.com",
"password": "$2b$10$FRHysk3eBMEOfS3FAT1nEe9voFH9yETR.3V1ZTJkg8Ekwtt6TlJ.W",
"createdAt": "2020-04-01T18:45:50.029Z",
"updatedAt": "2020-04-02T05:26:55.722Z",
"__v": 9
}
]
}
router.delete("/:id/delete", postsController.deletePost)
删除后控制器功能:
deletePost: async (req, res, next) => {
try {
const post = await Post.findByIdAndDelete(req.params.id)
if (!post) {
return res.status(200).json({ error: "No post found"})
}
res.status(200).json({ post })
} catch(error) {
console.log(error)
}
}
localhost:3000/api/v1/posts/5e857785591a6c1047341c60/delete
删除帖子后,我收到以下回复:
{
"post": {
"_id": "5e857785591a6c1047341c60",
"title": "helloooo",
"description": "hello there",
"user": "5e84e15ef2ae067df522c164",
"createdAt": "2020-04-02T05:26:29.637Z",
"updatedAt": "2020-04-02T05:26:29.637Z",
"__v": 0
}
}
现在,在我删除帖子后,我希望删除该ObjectID
帖子在users
集合中的引用。
现在,在数据库中,用户文档如下所示:
{
"_id" : ObjectId("5e84e15ef2ae067df522c164"),
"posts" :
[
ObjectId("5e857785591a6c1047341c60"),
ObjectId("5e85779f591a6c1047341c61")
],
"username" : "rick",
"email" : "rickk3@gmail.com",
"password" : "$2b$10$FRHysk3eBMEOfS3FAT1nEe9voFH9yETR.3V1ZTJkg8Ekwtt6TlJ.W",
"createdAt" : ISODate("2020-04-01T18:45:50.029Z"),
"updatedAt" : ISODate("2020-04-02T05:26:55.722Z"),
"__v" : 9
}
解决方案
因此,在您成功删除Post
调用集合以从数组user
中提取该特定帖子 ID 之后。posts
试试下面的代码:
const mongoose = require("mongoose");
deletePost: async (req, res, next) => {
try {
const post = await Post.findByIdAndDelete(req.params.id);
if (!post) {
return res.status(200).json({ error: "No post found" });
}
await User.update(
{ _id: mongoose.Types.ObjectId(post.user) },
{ $pull: { "posts": mongoose.Types.ObjectId(post._id) } }
); /** You can check for n updated to make sure this operation is successful or else can re-try again */
res.status(200).json({ post });
} catch (error) {
console.log(error);
}
};
推荐阅读
- django - 如何将 Django REST 框架中的错误(如 PK)更改为 ID
- ios - iOS OAuth2 客户端机密参数在 Google 凭据中不可用
- flutter - 应用程序购买中的颤振 iOS 无法在 testfly 中测试?
- nginx - Nginx 超时仅适用于子域
- django - 分页和查询集
- javascript - Express Session 不会取消设置变量
- java - 尝试在 .jar 导出文件中包含图像
- xaml - 如何在 UWP 中更改 ComboBox 占位符前景
- c# - 带有递归类的 C# 数据注释
- python - 使用 Gekko 最小化矩阵的范数