簡體   English   中英

如何返回當前用戶的出價數組

[英]How can I return an array of bids made by the current user

我有一組廣告,其中有一系列其他用戶對該特定廣告的出價對象。
我想返回的只是當前用戶的出價,因此它必須與req.user.id匹配(我持有 jwt 令牌的位置)
所以我嘗試了 filter 方法,但它返回了一個空數組,然后嘗試使用 for in 循環,得到另一組空方括號......


這是我的“廣告”收藏;
例如,從下面的集合中,我想獲取一個只包含出價的對象數組
由該用戶制作(用戶:5f7c40a0ec1a374c6c924610)。
 [ { "_id": "5f7d924371469c21f866fa16", "user": "5f7c40a0ec1a374c6c924610", "title": "Logistics for carrying chemicals", "text": "We need a approximately 20 trucks of logistics line for carrying our chemicals", "status": false, "company": "Bayrak Company", "location": "San Francisco", "date": "2020-10-07T10:02:43.811Z", "bids": [ { "_id": "5f7dc3225a835c359432ab15", "user": "5f7c40a0ec1a374c6c924610", "bid": "50000", "company": "Bayrak Company", "avatar": "https://gravatar.com/avatar/4ecfd3d216693adc6867bf09c9087b1a?d=mm&r=pg&s=200", "date": "2020-10-07T13:31:14.890Z" }, { "_id": "5f7db5fea762d34054072f8c", "user": "5f7c40a0ec1a374c6c924610", "bid": "50000", "company": "Bayrak Company", "avatar": "https://gravatar.com/avatar/4ecfd3d216693adc6867bf09c9087b1a?d=mm&r=pg&s=200", "date": "2020-10-07T12:35:10.237Z" } ], "comments": [], "__v": 2 }, { "_id": "5f7db0153870fd4178390a4d", "user": "5f7c40a0ec1a374c6c924610", "title": "Need construction trucks for new buildings", "text": "The new constrution area needs approximately 15 trucks", "status": false, "company": "Bayrak Company", "location": "San Francisco", "date": "2020-10-07T12:09:57.362Z", "bids": [], "comments": [], "__v": 0 } ]


**這是我到目前為止嘗試過的; **

 // @route GET /api/adverts/mybids // @desc Get bids that I made // @access Private. router.get('/mybids', auth, async (req, res) => { try { let adverts = await Advert.find(); let mybids = []; let bidsByMe = []; for (let x in adverts) { let bid = adverts[x].bids; for (let y in bid) { let innerBid = bid[y]; mybids.push(innerBid); } } for (let x in mybids) { let bid = mybids[x]; if (bid.user == req.user.id) { bidsByMe.push(bid); } } res.json(bidsByMe); } catch (err) { console.error(err.message); res.status(500).send('Server Error...'); } });

您可以運行此查詢:

  db.collection.aggregate([
 {
   $match: {
  user: "5f7c40a0ec1a374c6c924610",
  "bids.user": "5f7c40a0ec1a374c6c924610"
 }
},
{
$group: {
  _id: "$_id",
  user: {$first: "$user"},
  title: {$first: "$title"},
  text: {$first: "$text"},
  status: {$first: "$status"},
  location: {$first: "$location"},
  bids:{$first:"$bids"}
  
  }
}
 ])

//check below URL 

https://mongoplayground.net/p/TBGPDXO5lIl

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM