首页 > 解决方案 > 如何将新对象添加到我包含在我的配置文件模型中的空数组中(mongodb/mongoose)

问题描述

这是我的个人资料模型,

const ProfileSchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  company: String,
  website: String,
  location: String,
  status: {
    type: String,
    required: true,
  },
  skills: {
    type: [String],
    required: true,
  },
  bio: String,
  githubusername: String,
  experience: [
    {
      title: {
        type: String,
        required: true,
      },
      company: {
        type: String,
        required: true,
      },
      location: String,
      from: {
        type: Date,
        required: true,
      },
      to: Date,
      current: {
        type: Boolean,
        default: false,
      },
      description: String,
    },
  ],
  education: [
    {
      school: {
        type: String,
        required: true,
      },
      degree: {
        type: String,
        required: true,
      },
      fieldofstudy: {
        type: String,
        required: true,
      },
      from: {
        type: Date,
        required: true,
      },
      to: Date,
      current: {
        type: Boolean,
        default: false,
      },
      description: String,
    },
  ],
  social: {
    youtube: {
      type: String,
    },
    twitter: {
      type: String,
    },
    facebook: {
      type: String,
    },
    linkedin: {
      type: String,
    },
    instagram: {
      type: String,
    },
  },
  date: {
    type: Date,
    default: Date.now,
  },
  posts: [],
});

这就是我添加新帖子的方式,

router.post(
  "/",
  [auth, [check("text", "Text is required").not().isEmpty()]],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    try {
      const user = await User.findById(req.user.id).select("-password");

      let profile = await Profile.findOne({ user: req.user.id });
      if (profile) {

        const newPost = new Post({
          text: req.body.text,
          name: user.name,
          avatar: user.avatar,
          user: req.user.id,
        });

        const post = await newPost.save();
        profile.posts.unshift(post);
        res.json(post);
      }
    } catch (err) {
      console.error(err.message);
      res.status(500).json({ errors: [{ msg: "Server Error" }] });
    }
  }
);

大多数这些工作没有任何问题,我可以添加一个新帖子而没有任何错误,但是该帖子没有添加到我的个人资料中的帖子数组中。我想要的最终结果是记录用户的帖子,以便我可以在他的个人资料中单独显示它们。为什么这不起作用?请帮我!我是网络开发的新手,对此我感到很困惑。提前致谢。

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


第一步是检查您的身份验证中间件是否收到令牌参数,第二步是检查该令牌是否有效。最后是检查你的“router.post”逻辑。


推荐阅读