MongoDB: Cannot do exclusion on field in inclusion projection
Updated
•1 min readR
Working with Django and NodeJS, Based in New Delhi, Currently an SDE intern at LimeChat Previously worked with Fastjobs.
Cannot do exclusion on field `email` in inclusion projection
code: 31254,
You may get this type of error in MongoDB while using mongoose, Although it's not mongoose-specific. It's actually a MongoDB error, basically, we can't include and exclude fields simultaneously i.e at the same time
e.g.
const data = await Client.findById(id).select('name -email')
In this example, we want to include the name but exclude the email simultaneously. This is not possible hence the MongoDB throws an error.
But there is an exception here, According to Official MongoDB docs, only the _id field can be excluded while including other fields.
e.g.
const data = await Client.findById(id).select('name -_id')
This is perfectly fine.