node.js - 在 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 时会发生错误
解决方案
我认为您正在尝试访问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});
希望这会帮助你。
推荐阅读
- r - 如何在情节中旋转多类别x轴刻度标签?
- elasticsearch - Kibana 返回 200 代码但浏览器显示未就绪
- javascript - 如何将可编辑表的数据与其他数据一起从表单发送到控制器?
- laravel - Laravel Vapor 部署,然后无法响应请求
- ruby-on-rails - Rails 常量赋值
- c# - 具有可变秒数的 DateTime.ParseExact
- java - 无状态服务器如何在服务器端保持会话状态?
- javascript - 固定页脚重叠内容
- html - 用于在html中模糊图像的算法
- javascript - 通过 Javascript 功能实时编辑 HTML