j-p
j-p

Reputation: 3818

mongoose not projecting like docs say it should

I am experiencing some frustration - trying to return an nested array using findOne

with a model that looks like this

{
    _id: ObjectId,
    name: String,
    studies: []
}

Can someone tell me why a mongoose findOne is returning the _id field when I have not specified it?

module.exports.getStudies = function( id, callback ) {

    const query = {
        '_id': id
    };

    User.findOne( query, 'studies', callback );

}

this is returning

{
    "studies": [1,2,3],
    "_id": "5a9ccf7deccccc36d88b36ac"
}

when I am expecting

[1,2,3]

I apologize for the abrupt sounding tone of this question - I've just be at this a while and cannot make heads or tails of it.

Upvotes: 0

Views: 33

Answers (1)

Asaf Aviv
Asaf Aviv

Reputation: 11760

_id always return by default, you have to exclude it from the query.

module.exports.getStudies = function( id, callback ) {

    const query = {
        '_id': id
    };

    User.findOne( query, { studies: 1, _id: 0 }, callback );
}

Upvotes: 1

Related Questions