Maxime Arnould
Maxime Arnould

Reputation: 37

Get data from field containing reference

My "Post" schema is the following.

export const postSchema = new Schema({
  authorId: { type: ObjectId, required: true },
  images: { type: [String], required: true },
  note: { type: Number, default: null }, // maybe an "Note" documents array
  description: { type: String, required: true },
  comments: { type: [ObjectId], default: [] },
});

the authorId field contains the Id of a User document that have the following structure :

export const userSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  password: { type: String, required: true },
  stars: { type: Number, default: 0 },
  subscribers: { type: Number, default: 0 },
  subscriptions: { type: Number, default: 0 },
  avatar: {
    type: String,
    default: `http://localhost:4545/assets/images/avatars/default_avatar.jpg`,
  },
  posts: { type: [ObjectId], default: [] },
});

when I fetch my posts using:

const posts = await Post.find()

I would like to get the "name" , "avatar" and "_id" fields of the referenced User (author of the post).

I tried to map on my posts to fetch the author data using the authorId field without success. I would like to do it with agregates but I don't know it.

thanks a lot.

Upvotes: 2

Views: 316

Answers (1)

Arvind Pal
Arvind Pal

Reputation: 521

you have to use ref in postSchema like

authorId: { type: ObjectId, required: true , ref: "users"}

and while find Query you have to use populate

Post.find().populate('users')

here users is user collection

Upvotes: 2

Related Questions