首页 > 解决方案 > 如何在 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);

标签: node.jsreactjs

解决方案


该错误非常明确,您在comments数组中的一条评论没有content根据您的模型似乎需要的属性。

因此,通过调试/记录req.body.


推荐阅读