首页 > 解决方案 > 我得到承诺使用猫鼬 find() 函数时

问题描述

我创建了一个从 MongoDB 获取所有产品列表的函数。我正在使用猫鼬包。我正在尝试控制台记录它,但相反,我得到了 Promise 。这是我的代码: -

router.get('/', function (req,res) {

    //Gets all the products being sold by the particular seller
    const allProducts = findAllProducts(userId);
    console.log(allProducts);
})

async function findAllProducts(sellerId) {
    try {
        let products = await Products.find( { seller: {
            Id: sellerId
        }});   
        return products;     
    } catch (error) {
        console.log(e);
    }
}

标签: javascriptnode.jsexpressmongoosepromise

解决方案


您需要将 async/await 移至路由功能:

router.get('/', async function (req,res) {

    //Gets all the products being sold by the particular seller
    const allProducts = await findAllProducts(userId);
    console.log(allProducts);
})

function findAllProducts(sellerId) {
    try {
        return Products.find( { seller: {
            Id: sellerId
        }});   

    } catch (error) {
        console.log(e);
    }
}

推荐阅读