簡體   English   中英

Express 節點 - 將查找 ZCCADCDEDB567ABAE643E15DCF0974E503Z 的結果返回到變量

[英]Express Node - Return Results on Find Mongoose to variable

我要將 type_item 返回到客戶端,但我無法將 ZCCADCDEDB567ABAE643E15DCF0974E503Z 結果返回到變量 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> }

請幫助我...謝謝你:)

你得到一個 promise 所以你需要解決 promise 得到結果

你必須選擇:

  • 要么使用.then

    var items = Items.find().select('is_available total_stock exp_date').populate(populateQuery).limit(5).exec(yourfunction).then(result=>result).catch(err=>err)

  • 或者使用 Async await ES6 特性

您需要先使 function 異步,然后才能使用 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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM