猫鼬只返回文档的一个属性,而不是整个文档 [英] Mongoose return only one property of the document and not the entire document
本文介绍了猫鼬只返回文档的一个属性,而不是整个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
猫鼬为我们提供了许多查找文档的方法(findOne
,find
,findByID
等).所有这些方法都返回整个文档/模型.
Mongoose provides us lot of methods (findOne
, find
, findByID
, etc.) to find document(s). All these methods return the entire document(s)/model.
当我搜索文档时,是否仅从文档/模型返回单个属性而不是返回整个文档?
Is it possible that when I search for a document, I just return single property from the document/model instead of returning entire document?
推荐答案
是的,通过设置通常在条件对象之后指定的投影对象.
Yes, by setting the projection object, which is usually specified right after the criteria object.
MyModel.find({criteria: 'some criteria'}, {'fieldToInclude': 1, '_id': 0})
^ Projection object
注意:
默认情况下始终包含_id
,因此,如果需要,只需指定它的唯一排除项.
Note:
_id
is always included by default, so the only it's exclusion needs to be specified if needed.
这篇关于猫鼬只返回文档的一个属性,而不是整个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文