首页 > 解决方案 > 创建新帖子时如何保存用户文档?

问题描述

所以,我已经解决了之前的问题,只需要用帖子填充用户文档。当前用户文档如下所示:


        {
            "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" });
            }
        }

因为,保存在数据库中的用户文档有空的帖子数组,所以我无法填充它。请帮忙。

标签: node.jsmongodbexpressmongoosemongoose-populate

解决方案


将新帖子的 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 块的承诺。


推荐阅读