[英]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...我要将 type_item 返回到客户端,但我无法将 ZCCADCDEDB567ABAE643E15DCF0974E503Z 结果返回到变量 type_item[i].items,它什么也不返回...
How to return results from getting mongoose data to type_item?如何将获取 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
})
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你得到一个 promise 所以你需要解决 promise 得到结果
You have to options:你必须选择:
Either use.then要么使用.then
var items = Items.find().select('is_available total_stock exp_date').populate(populateQuery).limit(5).exec(yourfunction).then(result=>result).catch(err=>err) 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或者使用 Async await ES6 特性
You need to make the function async before you can use the await keyword您需要先使 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.