Node.js 通过一组对象的铁路超高贴图()

Node.js 通过一组对象的铁路超高贴图(),node.js,arrays,object,ejs,array.prototype.map,Node.js,Arrays,Object,Ejs,Array.prototype.map,我已经尝试解决这个问题很久了。 我正在将包含对象的数组保存到数据库中, 当我试图通过map()来检索对象的属性时,它只是不渲染任何内容 这是app.js代码: app.get("/:plasticcategory/product/:plasticproduct", (req, res) => { const plasticCategory = _.startCase(_.toLower(req.params.plasticcategory)); cons

我已经尝试解决这个问题很久了。 我正在将包含对象的数组保存到数据库中, 当我试图通过map()来检索对象的属性时,它只是不渲染任何内容

这是app.js代码:

app.get("/:plasticcategory/product/:plasticproduct", (req, res) => {

   const plasticCategory = _.startCase(_.toLower(req.params.plasticcategory));

   const plasticProduct =  req.params.plasticproduct;

   Product.find({category: plasticCategory, title: plasticProduct},'alt', (err, foundItem) => {

     if(err){

       console.log(err)

     }else {

       console.log(foundItem);

      res.render('alternatives', {altProduct: foundItem});

     }

   });

 });
当我运行console.log(foundItem)时,结果是
[{u id:5f5f5f9b2a9f999b1e9009072b,alt:[[Object]]}]

这是我的ejs代码(尝试呈现alt的数组对象属性:

    <% altProduct.map(alt => {%>

     <div class="col-lg-3">

       <h1><%=alt.altTitle %></h1>

       <img src="<%=alt.altImage%>" alt="alt-image">

       <a href="<%=alt.altUrl %>">Get it now!</a>

     </div>

    <% }) %>
{%>
“alt=”alt image“>

我添加了图像以使其更清晰,谢谢当您渲染模板时,我看到您这样称呼它:

res.render('alternatives', {altProduct: foundItem});
其中
foundItem
是数组
[{id:'something',alt:[{someObject}]}]

这是一个结果数组。每个结果都有一个名为“alt”的键,其中包含项。如果要同时呈现所有这些项,则需要将它们全部编译到单个数组中。(这称为“平面映射”)

产品回调的
else
块内开始。查找

const itemArrays = foundItem.map(item => item.alt); // Get the inner array from each result
const allAlternativeProducts = [].concat(...itemArrays); // Collect all these products into a single array
  res.render('alternatives', {altProduct: allAlternativeProducts});

尝试
console.log(JSON.stringify(foundItem))
,以确认
foundItem
具有您期望的属性?是的,它具有我期望的属性,我使用console.log(JSON.stringify(foundItem)检查了它通过我的mongoDB Cluster,两种解决方案都会出现以下错误:无法读取undefined@IdanAtias谢谢,我误解了
foundItem
的实际类型。我已经完全更新了我的答案。非常感谢,但我实际上正在尝试渲染每一个“alt”这与URL指定的类别和标题相匹配,如果我发布模型的架构会有帮助吗?好的,那么每个“alt”字段本身就是一个项目列表,每次调用
Product.find
都会检索多个这样的列表。听起来有一个步骤需要将这些列表收集到一个单独的l中是的,把答案重写一遍。