Sunday, 2 August 2020

How to add user's name as well as Id to users field in a chat?

I'm creating a web application that has chats, and users can join the chat. Once the user joins the chat, I want to add the user's ID as well as their name to the users field in the Chat schema. So far, I'm able to add their ID, but I am finding it difficult to add their name. Below, I have attached my Chat mongoose model, as well as my route to add a user to a chat. Also, I have attached my User mongoose model. Any help is greatly appreciated. Thank you!​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' }, name: { type: String, required: true } } ], 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); route to add user to chat:​// @route Put api/chats // @desc Add a user to a chat // @access Private router.put('/', [auth, [ check( 'code', 'Please include the code for the chat') .not() .isEmpty(), check( 'password', 'Please include the password for the chat' ).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.findOne({ code: req.body.code }); //const user = await User.findOne({ user: req.user.id }); if (!chat) { return res.status(400).json({ msg: 'Invalid Credentials' }); } // Check if the chat has already been joined by the user if (chat.users.filter(member => member.user.toString() === req.user.id).length > 0) { return res.status(400).json({ msg: 'Chat already joined' }); } //console.log(chat.password); const isMatch = await bcrypt.compare(req.body.password, chat.password); if (!isMatch) { return res.status(400).json({ errors: [{ msg: 'Invalid Credentials' }] }); } const newUser = { user: req.user.id, text: req.user.name } chat.users.unshift(newUser); await chat.save(); res.json(chat.users); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } }); ​User model:​const mongoose = require('mongoose'); const UserSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, date: { type: Date, default: Date.now } }); module.exports = User = mongoose.model('user', UserSchema);

Submitted August 03, 2020 at 03:18AM by dwight12345

No comments:

Post a Comment