在 mongodb 数据库中保存新帖子时发生错误

error occurs when saving new posts in mongodb database

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

通过这种方式将新的 post 保存到 post obj

时会发生错误

我认为您试图在不声明 post 对象的情况下访问 titlecontent。 所以你可以声明 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
    }; 

您只需按如下方式创建 Post,

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

希望对您有所帮助。

您可以先声明 User 对象,然后访问那些嵌套的属性,例如:

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

let newPost = new User();
newPost.post.title = title;
newPost.post.content = content;

或者,将其最小化为:

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

但是,由于这里的键和值都相同,您也可以使用对象-shorthand,例如:

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