You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何findById查询仅返回_id字段?技术咨询

Why does findById only return the _id field?

Let's break down the most likely causes for this issue, starting with the biggest red flag in your code:

1. You mixed up the parameter order for findById

Mongoose's findById method follows this signature:

Model.findById(id, projection, options)

You passed {lean: true} as the second parameter, which is reserved for projection rules (specifying which fields to include/exclude from the result). Since lean isn't a valid projection key, Mongoose ignores it and falls back to a default projection that only returns the _id field.

Fix it by correcting the parameter order:

You have two clean, valid ways to enable lean correctly:

  • Pass null as the projection (to return all fields) and move lean to the options parameter:
    return Role.findById(_id, null, {lean: true}).exec().then(...)
    
  • Use the chainable .lean() method (this is more readable and less error-prone):
    return Role.findById(_id).lean().exec().then(...)
    

2. Verify the actual document in MongoDB

While the parameter mix-up is the most probable cause, it's worth double-checking if the document really has the key field in your database. Run this query directly in the MongoDB shell:

db.roles.findOne({_id: ObjectId("5ade466c1384a4deffac6b09")})

If the result doesn't include a key field, then the issue is with the document itself, not your query logic.

3. Check your Mongoose Schema (less likely here)

If your Role Schema doesn't define the key field and has strict: true (the default setting), non-lean queries would omit the field—but since you're using lean (when configured correctly), it should return all fields present in the database. This is probably not the root issue here, but it's good to rule out.

Once you fix the parameter order for lean, your query should return the full document including the key field, and your cache logic will work as expected.

内容的提问来源于stack exchange,提问作者Alexander Mills

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:13:53