NodeJS Cant Map()通过对象数组

bnlyeluc  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(57)

我一直在尝试解决这个问题。我正在将一个包含对象的数组保存到我的数据库中。当我尝试通过它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)时,结果是[ { _id: 5f5f9b2a9f999b1e9009072b, 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>

    <% }) %>


我已经添加了图像,使其更清晰,谢谢<3 enter image description here

v8wbuo2f

v8wbuo2f1#

当你渲染模板时,我看到你这样调用它:

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

字符串
其中foundItem是数组[{ id: 'something', alt: [{ someObject }] }]
这是一个结果数组。每个结果都有一个名为'alt'的键,其中包含项目。如果你想将所有这些项目一起呈现,你需要将它们全部编译到一个数组中。(这称为'平面Map')
Product.find回调的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});

相关问题