I am working on a project where I have a chat between users. In my chat schema, I record the users who are a part of that chat.I want to add a profile for all of my users, however, the only thing inside of the profile is which chats they are a part of. Basically, what I want to do is when a user visits their profile page, I run through all of the chats to and see which chats contain that user. I then return JSON containing which chats they are in. I'm having difficulty with this however, particularly with how to go through all of the chats to find instances of the user. Currently, I'm doing this:const user = req.user.id; const chats = Chat.find(chat => chat.users.includes(user)); However, it is not working. What should I do instead. Additionally, below are my files for my Chat model, and my entire get profile method, to get the chats. Any help is appreciated!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); profile endpoint:router.get('/me', auth, async (req, res) => { try { const user = req.user.id; console.log(user); const chats = Chat.find(chat => chat.users.includes(user)); res.json(chats); } catch (err) { console.error(err.message); res.status(500).send('Server Error'); } });
Submitted July 28, 2020 at 02:08AM by dwight12345
No comments:
Post a Comment