I have written some code that successfully pulls the value from MongoDB, to check what has been sent to the API is the same price in MongoDB. In order to get the value from MondoDB, I have to use findbyID (a Mongoose function).
For some reason, despite using async and await, the validation checks are run before the value is returned from Mongoose's findById
function and the value from MongoDB is provided on the last line of the console log output, despite me thinking it should be the second console logged output.
Please could someone tell me how I can ensure the checks only begin after getting the dbPrice.price
value from MongoDB and assigning it to the DBPrice
variable?
Here's the code and the console output:
Code
var checkValidPrice = [];
req.body.products.map((item) => {
const itemPrice = item.price;
console.log(`item price: ${itemPrice}`);
async function checking() {
let dbPrice = await Product.findById(item.productId, "price");
console.log(`dbPrice: ${dbPrice.price}`);
if (itemPrice === dbPrice.price) {
return checkValidPrice.push("true");
} else {
return checkValidPrice.push("false");
}
}
checking();
console.log(`check price printing: ${checkValidPrice}`);
});
console.log(`func? ${checkValidPrice.includes("false")}`);
actual console output
item price: 350
check price printing:
func? false
dbPrice: 350
expected console output
item price: 350
dbPrice: 350
check price printing: true
func? false
EDIT:
I have replicated the logic explained in the commented questions, but they do not work. For example:
var checkValidPrice = await Promise.all(
req.body.products.map((item) => {
const itemPrice = item.price;
let dbPrice = Product.findById(item.productId, "price");
console.log("dbprice ", dbPrice.price);
if (itemPrice === dbPrice.price) {
return true;
} else {
return false;
}
})
);
console.log(`check price printing: ${checkValidPrice}`);