Saturday, 1 August 2020

Error with route that adds post to a chat.

I'm creating a website that has a bunch of chats and each chat has users. If you want to post to a chat, you have to be a member of that chat. Below I've included my add post route and my mongoose Chat model. When I try to post to a chat, I get a server error, and a message that says, "chat validation failed: posts.0.title: Path `title` is required., posts.0.text: Path `text` is required." Any help is very much appreciated. Thank you!​Add post route:// @route Post api/chats/:id // @desc Add a post to a chat // @access Private router.post('/:id', [ auth, [ check('text', 'Text is required') .not() .isEmpty(), check('title', 'Title is required') .not() .isEmpty() ] ], async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } try { const chat = await Chat.findById(req.params.id); if (!chat) { return res.status(400).json({ msg: 'Invalid Credentials' }); } let isMember = false; if (chat.users.filter(member => member.user.toString() === req.user.id).length > 0) { isMember = true; } if (!isMember) { return res.status(400).json('Invalid Credentials'); } /* const postFields = {}; postFields.title = req.body.title; postFields.text = req.body.text; */ const newPost = { title: req.body.title, text: req.body.text } chat.posts.unshift({ newPost }); await chat.save(); res.json(chat.posts); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } } ); Chat model:const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ChatSchema = new Schema({ title: { type: String, required: true }, password: { type: String, required: true }, creator: { type: Schema.Types.ObjectId, ref: 'user' }, users: [ { user: { type: Schema.Types.ObjectId, ref: 'user' } } ], code: { type: String, required: true }, posts: [ { text: { type: String, required: true }, title: { type: String, required: true }, date: { type: Date, default: Date.now } } ], date: { type: Date, default: Date.now } }); module.exports = Chat = mongoose.model('chat', ChatSchema);

Submitted August 01, 2020 at 10:56PM by dwight12345

No comments:

Post a Comment