首頁  >  問答  >  主體

使用mongodb查詢時,module.exports傳回undefined

我正在建立一個模組,用於使用 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粉957661544P粉957661544235 天前339

全部回覆(1)我來回復

  • P粉805931281

    P粉8059312812024-02-27 18:35:34

    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
        }
    }

    回覆
    0
  • 取消回覆