Open YACOUBI-Abdelhakime opened 1 month ago
import * as mongoose from 'mongoose';
import * as autopopulate from 'mongoose-autopopulate';
@Schema({
timestamps: true,
})
export class Chat {
@Prop()
participants: mongoose.Types.ObjectId[];
@Prop([{ type: mongoose.Schema.Types.ObjectId, ref: 'Message', autopopulate: true }])
messages: Message[];
@Prop()
lastMessageAt: Date;
}
const chatSchema = SchemaFactory.createForClass(Chat);
chatSchema.plugin(autopopulate); // Apply the autopopulate plugin to the schema
Explanation of autopopulate: true
Purpose:
When you have a reference to another document (like messages in your Chat schema, which references the Message model), you might want to include the full document in your query results instead of just the reference ID. Normally, you would have to call .populate('messages') manually in your query to achieve this.
autopopulate:
By setting autopopulate: true, Mongoose will automatically populate the referenced documents whenever the parent document is queried. This means that every time you fetch a Chat, the messages field will be automatically populated with the full Message documents, not just their IDs.