-->

Mongoose return only one property of the document

2019-08-09 07:52发布

问题:

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.