Automattic / Automattic/mongoose

Mongoose: Populating with projection using attribute of scheme

Open
#5,132 1 comment 0 reactions 0 assignees View on GitHub
new feature
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
35

Description

I triying the following **population/projection** and work fine

modelBaby.findOne({'userId': req.user.data._id, '_id': req.params.id})
.populate('categories._categoryId', {
levels:{
$elemMatch:{
name: 'PURPLE'
}
}
})

But i need name as a variable something like:

modelBaby.findOne({'userId': req.user.data._id, '_id': req.params.id})
.populate('categories._categoryId', {
levels:{
$elemMatch:{
// over heree !!
name: 'categories._levelName' or this._levelName
}
}
})

the scheme ref is

const babyCategory = new mongoose.Schema(
{
answer: {type: String},
_categoryId: {type: Schema.Types.ObjectId, required: true, ref: 'category'},
_categoryName: {type: String, required: true},
_levelName: {type: String, required: true}
},
{versionKey: false, _id : false}
);

**This is possible ?** or how is the best way to approach this

Thanks btw =D

Contributor guide

Open the contributing guide

Research direction

Start with the modelBaby.findOne().populate() query and the babyCategory schema shown in the issue, then read Mongoose population and projection documentation. Reproduce the fixed-name query and the variable-name case to establish the supported behavior; done means the issue has a confirmed capability answer or a documented recommended approach.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, nodejs
Domain
database
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.