简体   繁体   English

猫鼬对象:javascript地图功能无法添加新键

[英]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 我正在尝试从猫鼬查询返回的JSON数组上添加新密钥

  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 我要添加一个新的键taxAmount但它不会出现在数组中,但是, transactionObject=null可以正常工作,它是一个现有的键

What worked for me was to do result = JSON.parse(JSON.stringify(result)) or do: 对我result = JSON.parse(JSON.stringify(result))是执行result = JSON.parse(JSON.stringify(result))或执行以下操作:

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 ): 甚至更好地使用lean()https://mongoosejs.com/docs/api.html#query_Query-lean ):

Model.find().lean()

Quoting MDN's page on Array.prototype.map() (emphasis mine): 引用Array.prototype.map()上的MDN页面 (重点是我的):

The map() method creates a new array map()方法创建一个数组

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: 如果要使用上面.map的输出,则必须重新分配它:

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 ,并期望它具有新的键transactionObjecttaxAmount ,则可以重新分配result而无需更改以后的代码:

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

You should use lean() to prevent mongoose to hydrate the document. 您应该使用lean()来防止猫鼬使文档水化 Also map() function gets and returns an array. 同样map()函数获取并返回一个数组。 So I think it's better to use forEach() for the results. 因此,我认为最好使用forEach()获得结果。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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