MongoDB:请求带有 "select: false" 的字段以及所有标准字段
MongoDB: Request a field with "select: false" along with all standard fields
假设我们有一个用户模式:
name: String,
email: String,
mobile: { type: String, select: false }
db.User.findOne({ email })
returns name, email
说我也想请求mobile
,我调用db.User.findOne({ email }, { mobile: 1 })
不过,这个现在只returnsmobile
。如果我想请求所有标准字段,并添加一些默认具有 select: false
的特定字段怎么办?
当我实际上有几十个这样的字段时调用 db.User.findOne({ email }, { name: 1, email: 1, mobile: 1 })
是不合理的,并且必须在我的代码中进行类似的长调用。
谢谢!
使用.select('+mobile')
它会将{ projection: { mobile: 0 } }
变为{ 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')
假设我们有一个用户模式:
name: String,
email: String,
mobile: { type: String, select: false }
db.User.findOne({ email })
returns name, email
说我也想请求mobile
,我调用db.User.findOne({ email }, { mobile: 1 })
不过,这个现在只returnsmobile
。如果我想请求所有标准字段,并添加一些默认具有 select: false
的特定字段怎么办?
当我实际上有几十个这样的字段时调用 db.User.findOne({ email }, { name: 1, email: 1, mobile: 1 })
是不合理的,并且必须在我的代码中进行类似的长调用。
谢谢!
使用.select('+mobile')
它会将{ projection: { mobile: 0 } }
变为{ 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')