Goal: To retrieve all orders that contain the same products_id
Example: I want to retrieve all orders with products_id: 001 ; it returns all contents of _id:006 and _id:007
async function retrieveProductOrderInDb(uri_, user_info) {
try {
const client = await MongoClient.connect(uri_, {
useUnifiedTopology: true, serverApi: ServerApiVersion.v1
});
const db = client.db("boreal_db");
var orders_tb = db.collection("orders");
//retrieve all orders associated to product_id
const response = await orders_tb.find({"product_id": user_info.product_id},{
}).toArray();
client.close();
return response;
} catch(error) {
client.close();
console.log(error);
}
}
//RETRIEVE ORDERS WITH MY PRODUCTS
app.get("/retrieveProductOrder", (req, res) => {
res.set({ "Access-Control-Allow-Origin": "*" });
retrieveProductOrderInDb(uri, req.body).then((response) => {
res.send(response);
});
});
CodePudding user response:
You're pretty close to the solution! But there is one thing you forgot, you have to explicitly tell mongoDB what you are looking for. You mistyped the key name in the document. Actually it should have been products_id and you wrote product_id.
try this:
orders_tb.find({"products_id": user_info.product_id})
and you should know that in mongoDB the find method returns an array. Therefore, it is unnecessary to say toArray.