
目標:檢索所有包含相同 products_id 的訂單
示例:我想檢索所有帶有 products_id: 001 的訂單;它回傳 _id:006 和 _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);
});
});
uj5u.com熱心網友回復:
你非常接近解決方案!但是你忘記了一件事,你必須明確地告訴 mongoDB 你在找什么。您在檔案中輸入了錯誤的鍵名。實際上它應該是 products_id 而你寫的是 product_id。
嘗試這個:
orders_tb.find({"products_id": user_info.product_id})
你應該知道在 mongoDB 中 find 方法回傳一個陣列。因此,沒有必要說 toArray。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/451601.html
