Mongoose return only one property of the document and not the entire document

家住魔仙堡 提交于 2019-12-11 11:47:37

问题


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?


回答1:


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

Note: _id is always included by default, so the only it's exclusion needs to be specified if needed.



来源:https://stackoverflow.com/questions/31650258/mongoose-return-only-one-property-of-the-document-and-not-the-entire-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!