【发布时间】: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