如何解决nodejs中的等待问题

在这里,我试图从mongodb集合中获取最新的记录键p_id值,但是我遇到了类似:SyntaxError的错误:await仅在异步函数中有效。那么如何解决这个问题呢?

data.controller.js:

module.exports.getData = (req, res, next) => {
 var Product = mongoose.model(req.query.collectionname);
 const getid = await Product.findOne({ p_id: -1 }).limit(1)
 console.log(getid.p_id) 
}
评论
oautem
oautem

You need to make this function as an async function by putting async keyword in front of your function like bellow.

module.exports.getData = async(req, res, next) => {
 var Product = mongoose.model(req.query.collectionname);
 const getid = await Product.findOne({ p_id: -1 }).limit(1)
 console.log(getid.p_id) 
}
点赞
评论