I would like to know how to set the projection for a matched array of objects from a Mongoose query.
For example, if I have a Mongoose model that looks something like this:
var User = new Schema({ name: String, children: [Child] }); var Child = new Schema({ name: String, height: Number, age: Number, secret: Number });
In other words, an example JSON object that might result from this model:
User: { name: 'abc', children: [ { name: 'def', height: 123, age: 7, secret: 2 }, { name: 'ghi', height: 456, age: 9, secret: 3 } ] }
As you can see the model contains a property children
that is an array of Child
objects.
If I match only User
that contain an item in children
that has property name: 'def'
:
Users.find({ children.name: 'def' })
I can then set the projection to select properties (such as name
) and also properties from the matched object using a positional operator ($
):
.select({ name: 1, children.$: 1 }
The problem now is that with this projection, children.$
will always return the entire Child
object, including properties I may not want to query, such as secret
.
{ name: 'abc', children: [ { name: 'def', height: 123, age: 7, secret: 2 } ] }
Ideally I would like to be able to also select certain properties from the child
object obtained through $
similar to how name
was selected from the parent object User
, but I cannot find a way to do this.
One way to select a single property is to use the format children.$.age
but this can only be used to select 1 property, as doing it multiple times results in an error as you cannot use the poisitional $
operator multiple times.
.select({ name: 1, // and now select the height and age // but only of the child that matches name = 'def' // WITHOUT returning the entire object (exclude name and secret) children.$.age, children.$.height // error })
Is selecting the projection for an object obtained by the positional operator possible in Mongoose?