简体   繁体   中英

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

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()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM