text-dataset-tiny-code-script-py-format
/
ysnrfd_messenger
/BACKUP4
/backend
/src
/models
/Conversation.js
| const mongoose = require('mongoose'); | |
| const conversationSchema = new mongoose.Schema({ | |
| type: { | |
| type: String, | |
| enum: ['direct', 'group'], | |
| required: true | |
| }, | |
| name: { | |
| type: String, | |
| required: function() { return this.type !== 'direct'; } | |
| }, | |
| description: { | |
| type: String, | |
| maxlength: 500, | |
| default: '' | |
| }, | |
| avatar: { | |
| type: String, | |
| default: null | |
| }, | |
| createdBy: { | |
| type: mongoose.Schema.Types.ObjectId, | |
| ref: 'User', | |
| required: true | |
| }, | |
| participants: [{ | |
| user: { | |
| type: mongoose.Schema.Types.ObjectId, | |
| ref: 'User', | |
| required: true | |
| }, | |
| role: { | |
| type: String, | |
| enum: ['member', 'admin', 'owner'], | |
| default: 'member' | |
| }, | |
| joinedAt: { | |
| type: Date, | |
| default: Date.now | |
| }, | |
| lastRead: { | |
| type: Date, | |
| default: Date.now | |
| } | |
| }], | |
| lastMessage: { | |
| type: mongoose.Schema.Types.ObjectId, | |
| ref: 'Message', | |
| default: null | |
| }, | |
| settings: { | |
| isPublic: { | |
| type: Boolean, | |
| default: false | |
| }, | |
| allowInvites: { | |
| type: Boolean, | |
| default: true | |
| }, | |
| adminOnlyMessages: { | |
| type: Boolean, | |
| default: false | |
| } | |
| }, | |
| inviteLinks: [{ | |
| code: String, | |
| createdBy: mongoose.Schema.Types.ObjectId, | |
| expiresAt: Date, | |
| maxUses: Number, | |
| uses: { type: Number, default: 0 }, | |
| isActive: { type: Boolean, default: true }, | |
| createdAt: { type: Date, default: Date.now } | |
| }] | |
| }, { | |
| timestamps: true | |
| }); | |
| // Index for better performance | |
| conversationSchema.index({ 'participants.user': 1 }); | |
| conversationSchema.index({ type: 1, updatedAt: -1 }); | |
| conversationSchema.index({ lastMessage: 1 }); | |
| // Static method to find direct conversation between two users | |
| conversationSchema.statics.findDirectConversation = async function(userId1, userId2) { | |
| return this.findOne({ | |
| type: 'direct', | |
| 'participants.user': { $all: [userId1, userId2] }, | |
| $expr: { $eq: [{ $size: '$participants' }, 2] } | |
| }); | |
| }; | |
| module.exports = mongoose.model('Conversation', conversationSchema); |