因此,我已经解决了先前的问题,只需要在用户文档中填充帖子。当前用户文档如下所示:
{
"posts": [],
"_id": "5e75cf827ef14514f69c6714",
"username": "dio",
"email": "[email protected]",
"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: '[email protected]',
password: '$2b$10$fwV.KaZG.5tjtmMxQ9NNE.7.XAh6pzLFgf85z9BpPVOgFguR2inGO',
createdAt: 2020-03-21T08:25:38.459Z,
updatedAt: 2020-03-21T08:25:38.459Z,
__v: 0
}
[每次创建新帖子时,我都会将posts数组构造为包含用户刚创建的帖子的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添加到用户的posts数组后,需要保存用户:
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);
});
});
}
});
我记得