[英]How can I return an array of bids made by the current user
我有一组广告,其中有一系列其他用户对该特定广告的出价对象。
我想返回的只是当前用户的出价,因此它必须与req.user.id
匹配(我持有 jwt 令牌的位置)
所以我尝试了 filter 方法,但它返回了一个空数组,然后尝试使用 for in 循环,得到另一组空方括号......
[ { "_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.