Home > Software engineering >  How to return selected fields in mongodb?
How to return selected fields in mongodb?

Time:10-21

How can we limit the fields for each object that is being sent? Currently my response for each record is

{
            "_id": "614822f6badd4d55c8adcb6z",
            "name": "My life",
            "title": "lorem.....",
            "createdBy": "614593516c6a19d614971cae",
            "class": "613f23b026848c8934ffb52l",
            "createdAt": "2021-09-20T05:58:14.200Z",
            "updatedAt": "2021-09-20T07:38:57.160Z",
            "__v": 0,
        }

However for each object I only want to name and class only

CodePudding user response:

If you are using Mongoosejs then you can use projection option like

Model.find({}, 'name title'); // will return only _id, name, title

Ref: Model.find

  • Related