Mongoose return only one property of the document

2019-08-09 08:12发布

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条回答
太酷不给撩
2楼-- · 2019-08-09 08:24

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.

查看更多
登录 后发表回答