search

Home  >  Q&A  >  body text

module.exports returns undefined when querying with mongodb

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粉957661544P粉957661544276 days ago362

reply all(1)I'll reply

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

    reply
    0
  • Cancelreply