Javascript 如何返回当前用户的出价数组
我有一个广告集,里面有一系列其他用户对特定广告的出价对象Javascript 如何返回当前用户的出价数组,javascript,node.js,mongodb,nosql,Javascript,Node.js,Mongodb,Nosql,我有一个广告集,里面有一系列其他用户对特定广告的出价对象 我想返回的只是当前用户的出价,因此它必须与req.user.id(我持有jwt令牌的地方)匹配 所以我尝试了filter方法,但它返回了一个空数组,然后在循环中尝试了for,得到了另一个空的方括号集 这是我的“广告”收藏 例如,从下面的集合中,我想获得一个对象数组,其中只包含该用户(用户:5f7c40a0ec1a374c6c924610)的出价。 **这就是我迄今为止所做的尝试** 您可以运行此查询: db.collectio
我想返回的只是当前用户的出价,因此它必须与
req.user.id
(我持有jwt令牌的地方)匹配所以我尝试了filter方法,但它返回了一个空数组,然后在循环中尝试了for,得到了另一个空的方括号集
这是我的“广告”收藏
例如,从下面的集合中,我想获得一个对象数组,其中只包含该用户(用户:5f7c40a0ec1a374c6c924610)的出价
。
**这就是我迄今为止所做的尝试**
您可以运行此查询:
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
例如,使用
adverts.filter(ad=>ad.bids.some(bid=>bid.user==“…”)
获取包含用户出价的所有广告。当前代码的主要问题是不断更改并将单个对象推入数组;你需要创建一个新的bid对象,在每次找到一个对象时填充并推送它。我意识到缺少一个逻辑。。。因此,这里有一个快速更新,不要将代码放在注释中。问题来了,也解决了。现在,在我的广告模式中,用户的类型是ObjectId,另一方面,req.user.id是一个字符串,所以我将其转换为一个字符串,但它仍然转到else conditionOk,但是如果bid.user
已填充,因此包含用户对象,然后字符串化它将不会给您一个可以与req.user.id
进行比较的id字符串。你必须做if(bis.user.\u id==req.user.id)
,它还返回“comments”、“company”等字段。。。如何忽略rest?已更新查询,请检查,您可以在给定URL下检查结果
// @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