Home > Software engineering >  How to get mongoose schema result properly with missing field in JSON
How to get mongoose schema result properly with missing field in JSON

Time:10-28

I am new to Node.js and mongoose. I have tried a lot of things but not able to get the result I want.

Can someone help who knows how, who has faced this problem before or knows the solution of that problem?

Below is my database screen where 3 records are insured like below.

enter image description here

I have written this code and it returns the result shown below:

router.get("/categoryFields", async (request, response) => {
    const categories = await categoryModel.find({}).select("parentId title slug");
    try {
      response.send(categories);
    } catch (error) {
      response.status(500).send(error);
    }
  });

JSON result =>

[
    {
        "_id": "61779e5c1e4ed11e96301ccd",
        "title": "Clothing",
        "slug": "hello"
    },
    {
        "_id": "61779e8d1e4ed11e96301ccf",
        "parentId": "61779e5c1e4ed11e96301ccd",
        "title": "Shoe",
        "slug": ""
    },
    {
        "_id": "6177c1cd6d3e170ae58c89c3",
        "title": "Electric",
        "slug": ""
    }
]

But I need to get a result like this - I want parentID in every object:

[
    {
        "_id": "61779e5c1e4ed11e96301ccd",
        "parentId": "",
        "title": "Clothing",
        "slug": "hello"
    },
    {
        "_id": "61779e8d1e4ed11e96301ccf",
        "parentId": "61779e5c1e4ed11e96301ccd",
        "title": "Shoe",
        "slug": ""
    },
    {
        "_id": "6177c1cd6d3e170ae58c89c3",
        "parentId": "",
        "title": "Electric",
        "slug": ""
    }
]

Please can anyone help me how to do this in mongoose?

CodePudding user response:

db.collection.find({},
{
  "parentId": {
    $cond: {
      if: "$parentId",
      then: "$parentId",
      else: ""
    }
  },
  "title": 1,
  "slug": 1
})

Test Here

  • Related