【问题标题】:only one object being set to app.set() Expressjs只有一个对象被设置为 app.set() Expressjs
【发布时间】:2021-08-28 16:52:11
【问题描述】:

下午好, 我正在使用 MERN 堆栈制作一个简单的发票应用程序。 我有一个运行 2 forEach() 的函数,它通过数据库和用户中的发票。如果电子邮件匹配,则它会为该用户提供发票。 当我将 DBElement 记录到控制台时,它可以工作,它有正确的数据,但是当我将 test1 记录到控制台(app.get())时,它只有一个对象,而不是两者。

// forEach() function
 function matchUserAndInvoice(dbInvoices, dbUsers) {
    dbInvoices.forEach((DBElement) => {
      dbUsers.forEach((userElement) => {

        if(DBElement.customer_email === userElement.email){
           const arrayNew = [DBElement];
        arrayNew.push(DBElement);
        app.set('test', arrayNew);
        }
      })
    })

  }
  
  // end point that triggers the function and uses the data.
   app.get('/test', async (req,res) => {

      const invoices = app.get('Invoices');
      const users = await fetchUsersFromDB().catch((e) => {console.log(e)});

       matchUserAndInvoice(invoices,users,res);
       
      const test1 = await app.get('test');
      console.log(test1);
      res.json(test1);
    })

【问题讨论】:

  • 还要注意 matchUserAndInvoice() 是异步的,你不会等待它完成,所以即使其余代码是正确的(它不是),那么你的 console.log(test1) 不会显示上一次调用 matchUserAndInvoice() 的结果,因为它还没有完成它的工作。

标签: javascript node.js reactjs express for-loop


【解决方案1】:

function matchUserAndInvoice(dbInvoices, dbUsers) {
    let newArray = [];
    
    dbInvoices.forEach((DBElement) => {
      dbUsers.forEach(async(userElement) => {

        if(DBElement.customer_email === userElement.email){
         
          newArray.push(DBElement);
          app.set('test', newArray);
        }
      })
    })

  }

【讨论】:

    【解决方案2】:

    app.set('test', DBElement); 会覆盖现有的 DBElement,因此只有最后一个匹配的 DBElement 会显示在 test1 中。

    如果你想让test对应所有匹配的DBElement,你应该将它设置为一个数组,然后在for循环中每次匹配时将一个新的DBElement附加到数组中:

            if(DBElement.customer_email === userElement.email){
                let newArray = await app.get('test');
                newArray.push(DBElement);
                app.set('test', newArray);
            }
    

    【讨论】:

    • 保存 DBElement 以使其可供其他路线访问的最佳方法是什么?
    • @AS10 添加了向数组添加新元素的示例。
    • 我添加了我所拥有的,现在在我的原始代码中,它只是渲染同一个对象两次,DBElement 中有两个不同的对象
    • @AS10 你不应该有const arrayNew = [DBElement];,你应该从await app.get('test'); 获得初始值,正如我所展示的。
    • app.get(test) 不是一个数组,它只是一个对象。
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多