Home > Net >  Can't modify Mongoose data
Can't modify Mongoose data

Time:11-04

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

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

CodePudding user response:

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  });
      }
});

CodePudding user response:

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