0
exports.createDD_PR_addresstype = asyncHandler(async (req, res, next) => {

  const dropdowns = await DD_PR_addresstype.create(req.body);
  res.status(200).json({
    success: true,
    data: dropdowns
  });
});

replay

{
    "success": true,
    "data": {
        "_id": "5f252a444824ac0164195c1a",
        "label": "Battery",
        "company_id": "5f17e0f4d6eded0db090b272",
        "value": 1,
        "__v": 0
    }
}

i want to show only label and value. is there is any pre functions available to select created replay or i have to use seperate find query

prabhu
  • 878
  • 9
  • 17
Santhosh
  • 47
  • 7

1 Answers1

1

You could destructure the query response:

const { label, value } = await DD_PR_addresstype.create(req.body);

res.status(200).json({
  success: true,
  data: { label, value }
});

But that's just a way to write less code for:

data: {
  value: dropdowns.value,
  label: dropdowns.label
}

If you're looking for retrieving the document later with only the given props then the projection answer (which was deleted in between) is the way to go.

Since the other projection answer was deleted I add it here (using _id just as example):

const dropdowns = await DD_PR_addresstype.find( { _id: "5f252a444824ac0164195c1a" }, { label: 1, value: 1 } )
Getter Jetter
  • 2,033
  • 1
  • 16
  • 37
  • yeah the second method i did it for now but if the json replay body has many fields can i remove just one or two fields like selecting _id and remove it is possilbe? – Santhosh Aug 01 '20 at 11:11
  • 1
    like this? `const dropdowns = await DD_PR_addresstype.find( { _id: "5f252a444824ac0164195c1a" }, { _id: 0 } )` . This will return all props except `_id` – Getter Jetter Aug 01 '20 at 11:14
  • yeah in create method without calling second find query with id – Santhosh Aug 01 '20 at 11:17
  • 1
    I don't think you can use `projection` during create directly. But you could define a custom instance method for the Schema which saves your document and returns only the needed props. I'm not an expert there may also be other ways. See [here](https://stackoverflow.com/questions/36585080/how-to-add-schema-method-in-mongoose) – Getter Jetter Aug 01 '20 at 11:21