Search code examples
databasemongodbmongoosemongodb-querymongoose-schema

MongoDB: Request a field with "select: false" along with all standard fields


Say we have a user schema:

name: String,
email: String,
mobile: { type: String, select: false }

db.User.findOne({ email }) returns name, email

Say I want to also request mobile, I call db.User.findOne({ email }, { mobile: 1 })

However, this now only returns mobile. What if I want to request all of the standard fields, with the addition of some specific fields that have select: false by default?

It's not plausible to call db.User.findOne({ email }, { name: 1, email: 1, mobile: 1 }) when actually I have dozens of such fields, and would have to make similar long calls throughout my code.

Thanks!


Solution

  • Use .select('+mobile') it will change { projection: { mobile: 0 } } to { projection: { } }

    +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

    https://mongoosejs.com/docs/api.html#query_Query-select

    Specifies which document fields to include or exclude (also known as the query "projection")

    When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

    A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

    db.User.findOne({ email }).select('+mobile')