node.js - 无法通过 Mongoose 包含和排除查询字段

标签 node.js mongodb mongoose

我有一些架构并进行如下查询:

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

我希望文档只返回字段“one”。始终忽略字段“二”并其余。 然后我收到以下错误:

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

我正在动态生成字段字符串以包含或排除所需的字段。

如何消除错误。

最佳答案

这实际上与 Mongoose 无关。 “限制”存在于 mongo 本身。

来自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.

<小时/>

您可以包含、排除,但不能同时执行两者(_id 除外)

仅选择_id一个

'one'

选择除两个之外的所有字段

'-two'

异常(exception):仅选择一个不选择_id

'one -_id'

关于node.js - 无法通过 Mongoose 包含和排除查询字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22806027/

相关文章:

node.js - Mongoose FindOne 方法始终返回 'null'

node.js - NodeJS内存泄漏(async.queue和request)

mongodb - 如何从 MongoDB 数据库中删除用户

javascript - 比较出错了,或者说,这怎么可能是假的?

ruby - mongoid.yml 在哪里?

mongodb - 使用 mongoose 在 mongoDB 集合中保留单个文档

node.js - passport.js passport.initialize() 中间件未使用

node.js - Node 和 Mongodb - 每 24 小时运行一次脚本

node.js - 在 Node.JS 中使用 Passport 注册(注册)

node.js - 检测按键并替换控制台中的行