I’m creating a module for recording a purchased item on MongoDB using module.exports. This is my first time using this module.exports.
I need to return the results of the updateOne() query because I need to use the modifiedCount information on my main.js. However, the results are returning as undefined. I read that I should either use a callback or promise, with promise being better. How do I exactly do that on my case?
Here’s my code from 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;
And here’s how I’m calling it on the 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
}
2
Answers
Did "userid" exist when you update? And why return result when ‘result.modifiedCount > 0". In your case, db Promise didn’t get result,
and/or: maybe result not match your condition "modifiedCount > 0" and return nothing.
To fix, you should add condition when already success, and add async/await to get result first:
In main.js should be:
}