使用mongodb查詢時,module.exports傳回undefined
P粉957661544
P粉957661544 2024-02-26 21:36:14
0
1
336

我正在建立一個模組,用於使用 module.exports 在 MongoDB 上記錄購買的商品。這是我第一次使用這個 module.exports。

我需要傳回 updateOne() 查詢的結果,因為我需要在 main.js 上使用 moddedCount 資訊。然而,傳回的結果是未定義的。我讀到我應該使用回調或承諾,承諾更好。我該如何在我的案例中做到這一點?

這是我在 recordPurchase.js 模組中的程式碼:

const recordPurchase = (userid, item, price) => {
    db.collection("users").updateOne({ userid: userid }, { $push: { purchases: { item: item, price: price } } })
        .then((result) => {
            if (result.modifiedCount > 0) {
                console.log("Success");
                return result; //return the updateone information
            }
        })
        .catch((err) => {
            console.log("Error recording purchase: " err)
        })
}

module.exports = recordPurchase;

這是我在 main.js 上呼叫它的方式

if (msg.content === "test") {
    const userid = "12345";
    const item = "Some item name";
    const price = 10;
    const result = recordPurchase(userid, item, price)
    console.log(result); //returns updateone/result information
  }

P粉957661544
P粉957661544

全部回覆(1)
P粉805931281

const recordPurchase = (userid, item, price) => {
    return new Promise((resolve, reject) => {
        db.collection("users")
            .updateOne({userid: userid}, {$push: {purchases: {item: item, price: price}}})
            .then((result) => {
                if (result.modifiedCount > 0) {
                    resolve(result) // fulfilled
                } else {
                    reject("error") // rejected
                }
            })
            .catch(reject) // rejected
    })
}

module.exports = recordPurchase;

const recordPurchase = async (userid, item, price) => {
    try{
        const result = await db.collection("users").updateOne({userid: userid}, {$push: {purchases: {item: item, price: price}}})
        if (result.modifiedCount > 0) {
            return result
        }else{
            return new Error('error')
        }
    }catch (err){
        return err
    }
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!