【问题标题】:array not updating value when sending in response发送响应时数组不更新值
【发布时间】:2021-09-28 20:57:02
【问题描述】:

在获取每个项目图像后,我试图在 expressJs 路由内发回“projets”数组,但是当用更新的数组发回响应时,新添加的字段似乎不存在。

Ps:当我控制台记录添加的项目时,它会显示正确的更新项目。

var projets = await Annonce.find(
  { type_annonce: { $ne: "bien" }, deleted_at: { $eq: null } },
  null,
  { limit: 10, sort: { refreshed_at: -1 } }
);

for (let index = 0; index < projets.length; index++) {
  var images = await Image.find({ BienID: projets[index]._id });
  if (!images || images.length == 0) console.log("No images");
  else {
    projets[index].images = images;
  }
}

console.log(projets[1].images);
response.json({ annonces: projets });

【问题讨论】:

  • 您是说 JSON 响应仅包含 Annonce.find 结果而不包含添加的 .images
  • 提示:尝试console.log(JSON.stringify(projets));可能是你的一些项目没有任何图片。
  • @ChrisG 是的,他们都没有该图像字段,正在函数中创建它。
  • 如果您在response.json(...); 之前执行console.log(projets);,您会看到图像吗?
  • @ChrisG 是的,我通过创建一个新对象并将我需要返回的所有内容放入其中解决了这个问题。

标签: javascript arrays express object scope


【解决方案1】:

问题是“Annonce.find()”返回一个不可变对象,我只是将其结果分开以获得所需的结构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    相关资源
    最近更新 更多