node.js - 如何在 Nodejs 中发表评论
问题描述
我正在使用 Nodejs 和 React 创建应用程序,但注释功能不起作用。我不知道原因。
错误 :
板验证失败:comments.0.content:路径
content
是必需的。
我不知道为什么这不起作用。我犯了什么错误?
路线/api/board.js
router.post(
'/:id/comments',
[
auth,
[
check('content', 'input your content. ')
.not()
.isEmpty()
]
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() }, 'isEmpty');
}
try {
const user = await User.findById(req.user.id).select('-password');
const board = await Board.findById(req.params.id);
const newComment = new Board({
content: req.body.content,
user: req.user.id
});
board.comments.unshift(newComment);
await board.save();
res.json(board.comments);
} catch (err) {
console.error(err.message);
res.status(500).send('Server error!!');
}
}
);
模型/Board.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BoardSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
view_count: {
type: Number,
default: 1
},
created_at: {
type: Date,
default: Date.now
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'user'
}
}
],
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
content: {
type: String,
required: true
},
created_at: {
type: Date,
default: Date.now
}
}
]
});
module.exports = Board = mongoose.model('board', BoardSchema);
解决方案
该错误非常明确,您在comments
数组中的一条评论没有content
根据您的模型似乎需要的属性。
因此,通过调试/记录req.body
.
推荐阅读
- excel - 再次移动到下一列
- c# - 基于列检查和损坏的数据重写 linq 查询
- salesforce - 如何在 Salesforce 中使用自定义链接生成 PDF
- c++ - C ++如何将strcpy用于结构中的二维数组
- excel - 使用数组在工作表之间复制列
- javascript - Office js:我可以使用 Visual Studio 在我的 Word 插件中使用 Web 组件吗?
- java - iText7 自定义时间戳
- firebase - 如何乘以 Cloud Functions 超时时间?
- python - 在 Trimesh 中旋转网格
- android - 渲染像素流错误即将到来。但我的应用程序在颤振中运行良好