在阅读了关于我是否可以在promise句柄内执行mongoose查询的文档后,我有点困惑。在本例中,我试图循环遍历portfolio.coin中的一个对象数组,然后在另一个模型中查找它们的当前价格。有没有更好的方法来做这件事?下面的代码可以工作,但是我得到了Unhandledpromiserejection警告和documentnotfound错误。
// @route: GET api/portfolio/
// @description: Get the latest portfolio with price changes
// @access: Private
router.get('/', passport.authenticate('jwt',
{ session: false }), (req, res) => {
Portfolio.findOne({
user: req.user.id
}).then(portfolio => {
if (portfolio) {
// Loop over all the coins in the portfolio
portfolio.coin.forEach((item, index) => {
// In scope object
let details = {
_id: item._id,
exchange: item.exchange,
currencyname: item.currencyname,
currencyquantity: item.currencyquantity,
currencypaidwith: item.currencypaidwith,
pricepaid: item.pricepaid,
currentprice: 0,
pricedifference: 0
};
// For each coin find the market prices
Market.findOne({
exchange: item.exchange,
coin_one: item.currencyname,
coin_two: item.currencypaidwith
}).then(result => {
if (result) {
// details
details.currentprice = result.price;
details.pricedifference = result.price; // TODO: percentage
portfolio.coin[index] = details;
if (portfolio.coin.length >= index) {
portfolio.save().then(portfolio => res.json(portfolio)).catch(err => res.status(404).json({ nodoc: "somethin went wrong" }));
}
}
}).catch(err => res.status(404).json({ nodoc: "could not find a doc" }))
});
}
})
})
发布于 2018-06-10 01:12:05
您需要在最后一行添加.catch
// @route: GET api/portfolio/
// @description: Get the latest portfolio with price changes
// @access: Private
router.get('/', passport.authenticate('jwt',
{ session: false }), (req, res) => {
Portfolio.findOne({
user: req.user.id
}).then(portfolio => {
if (portfolio) {
// Loop over all the coins in the portfolio
portfolio.coin.forEach((item, index) => {
// In scope object
let details = {
_id: item._id,
exchange: item.exchange,
currencyname: item.currencyname,
currencyquantity: item.currencyquantity,
currencypaidwith: item.currencypaidwith,
pricepaid: item.pricepaid,
currentprice: 0,
pricedifference: 0
};
// For each coin find the market prices
Market.findOne({
exchange: item.exchange,
coin_one: item.currencyname,
coin_two: item.currencypaidwith
}).then(result => {
if (result) {
// details
details.currentprice = result.price;
details.pricedifference = result.price; // TODO: percentage
portfolio.coin[index] = details;
if (portfolio.coin.length >= index) {
portfolio.save().then(portfolio => res.json(portfolio)).catch(err => res.status(404).json({ nodoc: "somethin went wrong" }));
}
}
}).catch(err => res.status(404).json({ nodoc: "could not find a doc" }))
});
}
}).catch(err => res.status(404).json({ nodoc: "could not find a portfolio" }))
})
https://stackoverflow.com/questions/50776534
复制相似问题