简体   繁体   中英

Express Node - Return Results on Find Mongoose to variable

I'm going to return type_item to Client-side, but i can't return Mongoose results to variable type_item[i].items, it return nothing...

How to return results from getting mongoose data to 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
          })

The result when I log the Items

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

Please help me... Thank you:)

You are getting a promise so you need to resolve the promise to get the result

You have to options:

  • Either use.then

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

  • Or use Async await ES6 feature

You need to make the function async before you can use the await keyword

app.post("/routename", async(req,res)=>{

    var items = await Items.find()
        .select('is_available total_stock exp_date')
        .populate(populateQuery)
        .limit(5)
        .exec(//logic)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM