首页 > 解决方案 > 在 mongodb 数据库中保存新帖子时发生错误

问题描述

const userSchema = {
email: String,
password: String,
post:{
    title: String,
    content: String
}}; 

无法访问 post 字段并在其上保存数据如何假设

const title = req.body.title;
const content = req.body.content;

newPost = new User({
    post.title:title,
    content.content:content
});

通过这样做,将新帖子保存到帖子 obj 时会发生错误

标签: node.jsmongodbexpressejs

解决方案


我认为您正在尝试访问title并且content没有声明post对象。因此,您可以声明post对象并为每个属性分配值。

在您的情况下,没有content对象,您正尝试像 content.content.

请使用以下代码

  let post = {};

  newPost = new User({
     post.title:title,
     post.content:content
  });

还想建议您创建单独Post的架构,因为单个用户将有多个帖子,因此您不需要每次都创建用户。

例子

    const postSchema = {
        userId: { type: Schema.Types.ObjectId, ref: 'User' },
        title: String,
        content: String
    }; 

简单地说,您可以按如下方式创建帖子,

    const { title, content } = req.body;
    const userId = req.body.userId;// login user id or which user want to create a post

    newPost = new Post({ title, content});

希望这会帮助你。


推荐阅读