【问题标题】:Express Node - Return Results on Find Mongoose to variableExpress 节点 - 将 Find Mongoose 的结果返回到变量
【发布时间】:2020-07-26 18:27:09
【问题描述】:

我要将 type_item 返回到客户端,但我无法将 Mongoose 结果返回到变量 type_item[i].items,它什么也不返回...

如何将mongoose数据获取到type_item返回结果?

var type_item = [
  {
    type_name : "Item A",
    type : "1",
    items : []
  },
  {
    type_name : "Item B",
    type : "2",
    items : []
  },
  {
    type_name : "Item C",
    type : "3",
    items : []
  },
]
for (var i = 0; i < type_item.length; i++) {
  var populateQuery = {
      path: 'item',
      model: "Item",
      match: {
          type: type_item[i].type,
          is_publish: true
      },
      select: 'img_item merchant price item_name',
      populate: {
          path: 'merchant price',
          select: 'merchant_name usd_price eur_price'
      }
  }

  var items = VariantItems.find()
    .select('is_available total_stock exp_date')
    .populate(populateQuery)
    .limit(5)
    .exec(function (err, data) {
        if (err) {
            res.status(500).send(err)
        } else {
            var results = []
            for (var j = 0; j < data.length; j++) {
              if (data[j].merchant != null) {
                  results.push(data[j])
              } 
            }
            return results
        }
    })
  type_package[i].items = items
  console.log(items);
}
res.status(200).send({
              status: 200,
              iserror: false,
              message: 'Get List Items Success!',
              data: type_item
          })

我记录项目时的结果

Promise { <pending> }
Promise { <pending> }
Promise { <pending> }

请帮帮我... 谢谢你:)

【问题讨论】:

    标签: javascript node.js mongodb rest express


    【解决方案1】:

    你得到了一个承诺,所以你需要解决这个承诺才能得到结果

    你必须选择:

    • 要么使用.then

      var items = Items.find() .select('is_available total_stock exp_date') .populate(populateQuery) .limit(5) .exec(你的函数) .then(结果=>结果) .catch(err=>err)

    • 或者使用 Async await ES6 特性

    您需要先使函数异步,然后才能使用 await 关键字

    app.post("/routename", async(req,res)=>{
    
        var items = await Items.find()
            .select('is_available total_stock exp_date')
            .populate(populateQuery)
            .limit(5)
            .exec(//logic)
    }
    

    【讨论】:

    • 感谢您的回复,但它不起作用,当我控制台时结果仍然Promise { &lt;pending&gt; }
    • 你可以从问题中看到代码,重点是我要将type_item返回到客户端,但是我需要使用db中的数据设置type_item.items
    猜你喜欢
    • 2013-09-27
    • 2019-01-14
    • 2011-09-05
    • 1970-01-01
    • 2016-11-11
    • 1970-01-01
    • 2016-05-02
    相关资源
    最近更新 更多