YACOUBI-Abdelhakime / Study-Share

Support platform for students
http://study-share.s3-website.eu-west-3.amazonaws.com/
0 stars 0 forks source link

Use autopopulate: true, in schemas to populate childs model #2

Open YACOUBI-Abdelhakime opened 1 month ago

YACOUBI-Abdelhakime commented 1 month ago

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.

YACOUBI-Abdelhakime commented 1 month ago

Try this code 🥇

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