module.exports returns undefined when querying with mongodb
P粉957661544
P粉957661544 2024-02-26 21:36:14
0
1
364

I'm creating a module that records purchased items on MongoDB using module.exports. This is my first time using this module.exports.

I need to return the results of updateOne() query because I need moddedCount information on main.js. However, the result returned is undefined. I read that I should use callbacks or promises, promises are better. How can I do this in my case?

This is my code in the recordPurchase.js module:

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;

This is how I call it on 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

reply all(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
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template