--- # 9.1 MongoDB 資料管理 --- # 9.1 MongoDB 資料管理 ```javascript= const cartSchema = new mongoose.Schema({ p_id: { // 儲存來自 products 資料表的 _id type: mongoose.ObjectId, ref: 'products', required: [true, '缺少商品id'] }, quantity: { type: Number, min: [0, '商品數量不能小於0'], required: [true, '缺少商品數量'] } }, { versionKey: false }) ``` 使用者的資料,內部有陣列型的物件(需要定義格式,所以再用schema 定義) ![](https://i.imgur.com/dhw5fEJ.png) ![](https://i.imgur.com/atnPR61.png) --- ![](https://i.imgur.com/MPwqn86.png) --- ![](https://i.imgur.com/CsO3YvO.png) composition:內部的朝狀陣列 (實心稜形) aggregation:聚合(關聯) 不互相依存(空心稜形) ![](https://i.imgur.com/c3L4e2o.png) Query參數(網址後) ![](https://i.imgur.com/lsxc45A.png) ![](https://i.imgur.com/fIOCk0w.png) console.log(req.query) 透過Query傳值 ```javascript= const query = { $and: [] } if (req.query.priceGte) { const gte = parseInt(req.query.priceGte) if (!isNaN(gte)) { query.$and.push({ price: { $gte: gte } }) } } if (req.query.priceLte) { const lte = parseInt(req.query.priceLte) if (!isNaN(lte)) { query.$and.push({ price: { $lte: lte } }) } } if (req.query.keywords) { const keywords = req.query.keywords.split(',') const names = [] for (const keyword of keywords) { names.push(new RegExp(keyword, 'i')) } query.$and.push({ name: { $in: names } }) } const result = await products.find( query.$and.length > 0 ? query : {}, '-password' // { // $and: [ // { name: { $in: [/RTX/i, /asus/i] }} }, // { price: { $gte: 10 } }, // { price: { $lte: 300 } } // ]}, '-password' // // 上行為不要的,可改成要的多選: 'name email' ).sort({ price: -1 }) res.status(200).json({ success: true, message: '', result }) ``` --- :id (路由參數) ![](https://i.imgur.com/MsIcAMe.png) ---