shamon shamsudeen
shamon shamsudeen

Reputation: 5858

Mongoose object :javascript map function not working on adding new keys

I am trying to add a new key on the JSON array return from the mongoose query

  find({chatBotId:req.params.chatBotId}).
  populate('userPlan').
 .exec(function(err,result){

   result.map(function(e){           
      e.transactionObject =null
      e.taxAmount = 100;    
      return e;    
    });
})

I am adding a new key taxAmount but it does not appear the array, however, transactionObject=null works fine it's an existing key

Upvotes: 0

Views: 3287

Answers (3)

Ehsan
Ehsan

Reputation: 335

You should use lean() to prevent mongoose to hydrate the document. Also map() function gets and returns an array. So I think it's better to use forEach() for the results.

results = Document.find({chatBotId:req.params.chatBotId})
 .populate('userPlan')
 .lean()
 .exec(function(err,results){
   results.forEach(function(e){           
      e.transactionObject = null
      e.taxAmount = 100
    });
})

Upvotes: 2

user1665355
user1665355

Reputation: 3393

What worked for me was to do result = JSON.parse(JSON.stringify(result)) or do:

result = result.map(function (e) {
  e = e.toJSON(); // toJSON() here.
  e.transactionObject = null;
  e.taxAmount = 100;
  return e;
});

Or even better use lean() (https://mongoosejs.com/docs/api.html#query_Query-lean):

Model.find().lean()

Upvotes: 4

user3310334
user3310334

Reputation:

Quoting MDN's page on Array.prototype.map() (emphasis mine):

The map() method creates a new array

Your code

result.map(function(e){           
  e.transactionObject =null
  e.taxAmount = 100;    
  return e;    
});

doesn't actually do anything.

If you want to use the output of the .map above you have to re-assign it:

arrayWithNewKeys = result.map(function (e) {
  e.transactionObject = null
  e.taxAmount = 100;
  return e;
});

If you are using result later, expecting it to have the new keys transactionObject and taxAmount, you can re-assign result without needing to change your later code:

result = result.map(function (e) {
  e.transactionObject = null
  e.taxAmount = 100;
  return e;
});

Upvotes: 0

Related Questions