Skip to content

Conversation

@SMK-07
Copy link

@SMK-07 SMK-07 commented Dec 3, 2025

Added support for an as option in populate(). This allows you to populate a path but assign the result to a different property, keeping the original path as-is. This is useful when you want to keep the foreign key (ObjectId) but also have the populated document available on the same object, without defining duplicate fields in the schema.

Examples

const schema = new Schema({
  authorId: { type: Schema.Types.ObjectId, ref: 'User' }
});
const BlogPost = mongoose.model('BlogPost', schema);

const post = await BlogPost.findOne().populate({
  path: 'authorId',
  as: 'author'
});

// post.authorId is still the ObjectId
// post.author is the populated User document
console.log(post.authorId); // 507f1f77bcf86cd799439011
console.log(post.author.name); // 'Val'

This works with lean(), arrays, and nested paths as well.

Copy link
Collaborator

@AbdelrahmanHafez AbdelrahmanHafez left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please revert all unrelated formatting changes, this is difficult to review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants