node.js - 创建新帖子时如何保存用户文档?
问题描述
所以,我已经解决了之前的问题,只需要用帖子填充用户文档。当前用户文档如下所示:
{
"posts": [],
"_id": "5e75cf827ef14514f69c6714",
"username": "dio",
"email": "dio123@gmail.com",
"password": "$2b$10$fwV.KaZG.5tjtmMxQ9NNE.7.XAh6pzLFgf85z9BpPVOgFguR2inGO",
"createdAt": "2020-03-21T08:25:38.459Z",
"updatedAt": "2020-03-21T08:25:38.459Z",
"__v": 0
}
所以,我在创建帖子时这样做了,以便以后能够填充它。
newPost: (req, res) => {
const data = {
title: req.body.title,
content: req.body.content,
user: req.user.userId
}
Post.create(data, (err, newPost) => {
console.log(data, "data")
if (err) {
return res.status(500).json({ error: err })
} else if (!newPost) {
return res.status(400).json({ message: "No Post found" })
} else if (newPost) {
User.findById(req.user.userId, (err, user) => {
user.Posts = user.Posts.concat(newPost._id)
return res.status(200).json({ newPost, user })
})
}
})
}
当我从上面的 return 语句返回用户时,这样做之后,它看起来像这样:
{
posts: [ 5e75d89fa048e321f704453b ],
_id: 5e75cf827ef14514f69c6714,
username: 'dio',
email: 'dio123@gmail.com',
password: '$2b$10$fwV.KaZG.5tjtmMxQ9NNE.7.XAh6pzLFgf85z9BpPVOgFguR2inGO',
createdAt: 2020-03-21T08:25:38.459Z,
updatedAt: 2020-03-21T08:25:38.459Z,
__v: 0
}
每次我创建一个新帖子时,我都希望帖子数组包含用户刚刚创建的帖子的 objectID,但它只是推送最新帖子的 objectId。为什么它不记得以前的?
另外,我想获取用户的帖子:
getUserPosts: async (req, res) => {
try {
const user = await User.findById(req.params.id).populate("posts");
if (!user) {
return res.status(400).json({ error: "No user" });
}
return res.status(200).json({ userPosts: user.posts });
} catch (err) {
return res.status(500).json({ error: "Server error" });
}
}
因为,保存在数据库中的用户文档有空的帖子数组,所以我无法填充它。请帮忙。
解决方案
将新帖子的 id 添加到用户的帖子数组后,您需要保存用户:
Post.create(data, (err, newPost) => {
console.log(data, "data");
if (err) {
return res.status(500).json({ error: err });
} else if (!newPost) {
return res.status(400).json({ message: "No Post found" });
} else if (newPost) {
User.findById(req.user.userId, (err, user) => {
user.posts.push(newPost._id);
user
.save()
.then(() => {
return res.status(200).json({ newPost, user });
})
.catch(err => {
return res.status(500).json({ error: err });
console.log(err);
});
});
}
});
我记得在您之前的问题中,帖子字段的名称posts
不在Posts
用户模式中,因此以下行很重要,我们也使用 push 方法而不是 concat:
user.posts.push(newPost._id);
在此之后,我们只需要使用save
方法保存用户,因为保存方法返回一个我添加 then catch 块的承诺。
推荐阅读
- java - 连接到 Firebase 时无法同步 Gradle
- python - 如何用没有数据的列重构数据框
- flutter - 在 main 中发送一个参数并在小部件的构建中使用它(Flutter dart)
- unix - 如何在 Unix 的 head 和 tail 之间添加换行符?
- sqlite - 如何在一个 sql 表中加入所有内容并从另一个表中第一次出现,保留所有来自第一个表
- python - tensorflow 数据集在过滤后无法计算出 epoch 中的训练步数
- android - 当我收到意图时额外丢失
- c++ - 如何在我的 C++ 程序中链接和使用远程 cplex
- java - 单例 bean 是否与 Spring 中的所有用户共享数据?
- python-3.x - 如何将 def common_stats 集成到类 Data_Load 中?