How to findAll by a specific variable in MongoDB?
I have the following MongoDB collection of bets:
{
id: String,
user_id: String,
type: String,
events: [{
eventID: String,
sport: String,
evento: String,
aposta: String,
estado: String,
odd: String
}],
total_odd: String,
bet_ammount: String,
state: String,
date: String
}
My goal is to send an HTTP request into /bet and reply with all the bets in my Database that correspond to the given "user_id" that is sent in the initial request.
For example, if there were 3 bets that had the user_id with "61e0eb548714ee662c2d76d1", I would want to to send all 3 bets in the body of the reply. I've had a similar request where I would only need to send a specific bet according to it's ID. The code for that is the following:
router.get('/bet', (req, res, next) => {
let token = req.headers.token;
jwt.verify(token, 'secretkey', (error, decoded) =>{
if (error) return res.status(401).json({
title: 'Unauthorized'
})
BetModel.findOne({ user_id: decoded.userId }, (error, bet) => {
if (error) return console.log(error)
return res.status(200).json({
title: 'Bets Grabbed',
bet:{
_id: bet._id,
events: bet.events,
total_odd: bet.total_odd,
bet_amount: bet.bet_amount,
state: bet.state,
date: bet.date,
user_id: bet.user_id
}
})
})
})
});
How could I change this to initially get every bet for that specific user_id and then send them all in the HTTP reply?
You can create another route that changes the findOne
query to find
, and sends the result to the HTTP reply.
BetModel.find({ user_id: decoded.userId }, (error, bets) => {
if (error) return console.log(error)
return res.status(200).json({
title: 'Bets Grabbed',
bets: bets
})
})
You could then iterate through each of the bets on the frontend.