Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to include and exclude fields of query via mongoose

I have some schema and making query as following :

mongoose.model('mymodel').find({}, 'one -two -__v', function(err,docs){});

I want documents should only return the field 'one'. Always ignore the fields 'two' and rest all. Then i get the following error :

You cannot currently mix including and excluding fields. Contact us if this is an issue.

I am generating the field string dynamically to include or exclude the fields required.

How to get rid of the error.

like image 738
codeofnode Avatar asked Jan 27 '26 14:01

codeofnode


1 Answers

This actually has nothing to do with mongoose. The "limitation" exists within mongo itself.

From the collection.find documentation

A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field. In projections that explicitly include fields, the _id field is the only field that you can explicitly exclude.


You either include, or exclude, you can't do both, (with the exception of _id)

Select only _id and one

'one'

Select all fields except for two

'-two'

Exception: Select only one without _id

'one -_id'
like image 169
maček Avatar answered Jan 29 '26 04:01

maček



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!