Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't modify Mongoose data

I have this code:

router.post('/BWreport', async function(req, res, next){
     try{
        var cname = await corporate.find().select('corporateID username');
        cname.forEach(function(cname, await){
          cname["totalcases"] = 1;
        });
        return res.json({ response:true, data:cname });
      }catch(err){
        return res.json({ response:false, data:err  });
      }
});

As you can see in the output, totalcases is not getting added:

    "response": true,
    "data": [
        {
            "_id": "61d3f90340b6cad5974ca50a",
            "username": "SB Demo",
            "corporateID": "SB00001"
        },
        {
            "_id": "62266f20fa0eb7a8fbe7d82a",
            "corporateID": "SB00002",
            "username": "NeoGrowth"
        }]

as you can see new key/value pair not getting in output, can anyone tell me why?
desired output below

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    "response": true,
    "data": [
        {
            "_id": "61d3f90340b6cad5974ca50a",
            "username": "SB Demo",
            "corporateID": "SB00001",
            "totalcases": "1"
        },
        {
            "_id": "62266f20fa0eb7a8fbe7d82a",
            "corporateID": "SB00002",
            "username": "NeoGrowth",
            "totalcases": "1"
        }]

>Solution :

Mongoose documents are immutable. Use .lean() to make it return a Javascript object that can be modified:

router.post('/BWreport', async function(req, res, next){
     try{
        var cname = await corporate.find().select('corporateID username').lean();

        cname.forEach(function(c, await){
          c["totalcases"] = 1;
        });

        return res.json({ response:true, data:cname });
        }catch(err){
        return res.json({ response:false, data:err  });
      }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading