Related
So I can call the variable "teams" and see the data fine but I can't get the values from it in my {#each} block. I know its not part of the "fixtures" variable I'm iterating through and tbh that's probably the issue.
Does anyone know how I can get the actual values within "teams" instead of getting 'undefined' or a better way of fetching multiple arrays within themselves? (ill put the example at the bottom)
my +page.svelte
<script>
export let data;
const { fixtures } = data;
const teams = fixtures.flatMap(fixtures => fixtures.participants)
console.log(teams)
</script>
<div class="flex flex-col absolute top-[0] right-0 w-[85vw] p-6">
<div class="">
{#each fixtures as fixture}
<p>{fixture.name}</p>
<div class="">{fixture.home_score}{fixture.away_score}</div>
<p>{teams.short_code}</p>
{/each}
</div>
</div>
+page.server.js
export const load = async () => {
const fetchList= async () => {
const url = `https://api.sportmonks.com/v3/football/schedules/seasons/19734?api_token=${process.env.API_KEY}`;
const res = await fetch(url);
const data = await res.json()
return data.data.flatMap(data => data.rounds.map(rounds => rounds.fixtures)).flat()
}
return {
fixtures: fetchList(),
}
}
The API
{
"data": [
{
"id": 77457864,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"type_id": 223,
"name": "Regular Season",
"sort_order": 1,
"finished": false,
"is_current": true,
"starting_at": "2022-08-05",
"ending_at": "2023-05-28",
"rounds": [
{
"id": 274668,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"name": "1",
"finished": true,
"is_current": false,
"starting_at": "2022-08-05",
"ending_at": "2022-08-07",
"fixtures": [
{
"id": 18535049,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"group_id": null,
"aggregate_id": null,
"round_id": 274668,
"state_id": 5,
"venue_id": 206,
"name": "Manchester United vs Brighton & Hove Albion",
"home_score": 1,
"away_score": 2,
"starting_at": "2022-08-07 13:00:00",
"result_info": "Brighton & Hove Albion won after full-time.",
"leg": "1/1",
"details": null,
"length": 90,
"placeholder": false,
"last_processed_at": "2022-12-05 09:15:37",
"starting_at_timestamp": 1659877200,
"participants": [
{
"id": 14,
"sport_id": 1,
"country_id": 462,
"venue_id": 206,
"gender": "male",
"name": "Manchester United",
"short_code": "MUN",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/14.png",
"founded": 1878,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-10 17:00:00",
"meta": {
"location": "home"
}
},
{
"id": 78,
"sport_id": 1,
"country_id": 462,
"venue_id": 480,
"gender": "male",
"name": "Brighton & Hove Albion",
"short_code": "BRH",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/78.png",
"founded": 1901,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-08 13:00:00",
"meta": {
"location": "away"
}
}
]
},
There's a "dirty" way to do it with {#key}
In a GET request I am using a spread operator in a for loop but it is showing only the last entered data only(data about seats) from the database.
The GET request:
router.get("/trip/single", async (req, res) => {
if (!req.query.from || !req.query.to || !req.query.date) {
return res.send({
error: "Please enter the data to get the trip",
});
}
const { from, to, date } = req.query;
const routes = await Route.find({
"Location.from": from,
"Location.to": to,
date: date.toString(),
});
const matchedBus = await routes.filter(() => {
return Route.busId === routes._id;
});
const bookings = await Booking.find({
routeId: { $in: matchedBus.map((matchedBus) => matchedBus._id) },
});
const busIdWithSeatsObj = {};
for (let i = 0; i < matchedBus.length; i++) {
let currentBusSeats = [];
const busBookings = routes.map((route) => {
return route.date === date && route.busId === matchedBus[i].busId;
});
bookings.forEach((booking) => {
currentBusSeats = [...booking.seatNumbers];
});
busIdWithSeatsObj[matchedBus[i].busId] = currentBusSeats;
}
res.status(200).send({ routes, matchedBus, busIdWithSeatsObj });
});
I have two collections into the database:
{"_id":{"$oid":"629a0efd4202a387c33186f9"},
"userId":{"$oid":"629a0e044202a387c33186e7"},
"routeId":{"$oid":"629a0ea54202a387c33186f5"},
"passengers": [{"name": "mitul","gender": "male","age": 25, "_id": {"$oid": "629a0efd4202a387c33186fa"}}],
"phone": 7984154363,
"email":"mitulkheni695#gmail.com",
"bookingDate":"2022-06-01",
"fare": 2500,
"seatNumbers": [1, 2, 3, 4, 5],
"departureDetails": [{"city": "surat","location": "kapodra","time": "8:00:00", "date": "2022-06-03","_id": {"$oid": "629a0efd4202a387c33186fb"}}],
"arrivalDetails": [{"city":"bhavnagar", "location": "paravadi", "time": "12:00:00", "date": "2022-06-03","_id": {"$oid":"629a0efd4202a387c33186fc"}}],
"createdAt":{"$date":"2022-06-03T13:39:09.223Z"},
"updatedAt":{"$date": "2022-06-03T13:39:09.223Z"},
"__v": 0}
{"_id": {"$oid": "629ac54b13b8d8cd52fc743d"},
"userId":{"$oid":"629a0e044202a387c33186e7"},
"routeId":{"$oid":"629a0ea54202a387c33186f5"},
"passengers":[{"name": "dhaval", "gender": "male", "age": 24, "_id": { "$oid": "629ac54b13b8d8cd52fc743e" }}],
"phone": 7984154363,
"email":"dhaval#gmail.com",
"bookingDate": "2022-06-04",
"fare": 1000,
"seatNumbers": [14, 15],
"departureDetails":[{"city": "surat", "location": "laskana", "time":"8:00:00", "date": "2022-06-03", "_id": { "$oid": "629ac54b13b8d8cd52fc743f" }}],
"arrivalDetails": [{"city": "bhavnagar", "location": "sukhpar", "time": "12:00:00", "date": "2022-06-03", "_id": { "$oid": "629ac54b13b8d8cd52fc7440" }}],
"createdAt": {"$date": "2022-06-04T02:36:59.215Z"},
"updatedAt": {"$date": "2022-06-04T02:36:59.215Z"},
"__v": 0}
In this collections both have same routeId.
I should get this result with all the seats that are already booked for this particular bus:
{
"routes": [
{
"Location": {
"from": "629a0e544202a387c33186f2",
"to": "629a0e294202a387c33186ef"
},
"_id": "629a0ea54202a387c33186f5",
"busId": "629a0e184202a387c33186ec",
"date": "2022-06-03",
"departureTime": 8,
"arrivalTime": 12,
"createdAt": "2022-06-03T13:37:41.993Z",
"updatedAt": "2022-06-03T13:37:41.993Z",
"__v": 0
}
],
"matchedBus": [
{
"Location": {
"from": "629a0e544202a387c33186f2",
"to": "629a0e294202a387c33186ef"
},
"_id": "629a0ea54202a387c33186f5",
"busId": "629a0e184202a387c33186ec",
"date": "2022-06-03",
"departureTime": 8,
"arrivalTime": 12,
"createdAt": "2022-06-03T13:37:41.993Z",
"updatedAt": "2022-06-03T13:37:41.993Z",
"__v": 0
}
],
"busIdWithSeatsObj": {
"629a0e184202a387c33186ec": [
1,
2,
3,
4,
5,
14,
15
]
}
}
But instead I am getting this result with last entered data only:
{
"routes": [
{
"Location": {
"from": "629a0e544202a387c33186f2",
"to": "629a0e294202a387c33186ef"
},
"_id": "629a0ea54202a387c33186f5",
"busId": "629a0e184202a387c33186ec",
"date": "2022-06-03",
"departureTime": 8,
"arrivalTime": 12,
"createdAt": "2022-06-03T13:37:41.993Z",
"updatedAt": "2022-06-03T13:37:41.993Z",
"__v": 0
}
],
"matchedBus": [
{
"Location": {
"from": "629a0e544202a387c33186f2",
"to": "629a0e294202a387c33186ef"
},
"_id": "629a0ea54202a387c33186f5",
"busId": "629a0e184202a387c33186ec",
"date": "2022-06-03",
"departureTime": 8,
"arrivalTime": 12,
"createdAt": "2022-06-03T13:37:41.993Z",
"updatedAt": "2022-06-03T13:37:41.993Z",
"__v": 0
}
],
"busIdWithSeatsObj": {
"629a0e184202a387c33186ec": [
14,
15
]
}
}
In the for loop you are overwriting the currentBusSeats array with a new array instead of appending to it. You create a new array and overwrite the old currentBusSeats here:
currentBusSeats = [...booking.seatNumbers];
To add to the booking.seatNumbers you can use Array.push:
currentBusSeats.push(...booking.seatNumbers);
Side note: Now you can also declare currentBusSeats as a const instead of a variable with let, which would have helped you debugging by getting an error that you tried to overwrite an array (Assignment to constant variable). I think it is good practice to always declare objects and arrays as constants because you hardly want to overwrite them, only change the values.
I have a collection like that:
{
"_id": {
"$oid": "5f54b3333367b91bd09f4485"
},
"products": [
{
"_id": 20,
"name": "Türk Kahvesi",
"price": 8,
"count": 2
},
{
"_id": 22,
"name": "Dibek",
"price": 10,
"count": 2
},
{
"_id": 21,
"name": "Damla Sakızlı T.K.",
"price": 10,
"count": 1
}
],
"deskId": "5f53473611f7490d3c860ccd",
"waiterId": "1",
"deskName": "Ü2",
},
{
"_id": {
"$oid": "5f54af663367b91bd09f4483"
},
"products": [
{
"_id": 20,
"name": "Türk Kahvesi",
"price": 8,
"count": 1
},
{
"_id": 21,
"name": "Damla Sakızlı T.K.",
"price": 10,
"count": 1
},
{
"_id": 22,
"name": "Dibek",
"price": 10,
"count": 1
},
{
"_id": 23,
"name": "Menengiç",
"price": 10,
"count": 1
},
{
"_id": 25,
"name": "Double Espresso",
"price": 15,
"count": 6
}
],
"deskId": "5f53473611f7490d3c860ccd",
"waiterId": "1",
"deskName": "Ü2",
}
And my goal is, getting all data order and group by product._id and show totalPrice(price*count),products.name, _id and totalCount. This is actually to show us a report product by product. If you need any more information, Just ask. Sample result:
{
{
"_id": 20,
"name": "Türk Kahvesi",
"totalCount": 3,
"totalPrice": 24
},
{
"_id": 22,
"name": "Dibek",
"totalCount": 3,
"totalPrice": 30
},
{
"_id": 21,
"name": "Damla Sakızlı T.K.",
"totalCount": 2,
"totalPrice": 20
},
{
"_id": 23,
"name": "Menengiç",
"totalCount": 1,
"totalPrice": 10
},
{
"_id": 25,
"name": "Double Espresso",
"totalCount": 6,
"totalPrice": 90
}
}
We can use aggregate on something. Please help me.
I'm still new to MongoDB, but I think this aggregate pipeline is what you're looking for. That said this is the kind of thing you should research yourself using the documentation, but as long as you understand the thought process you'll learn something so it's all good!
[
{
$unwind: {
path: '$products',
// Here we are seperating each item in the products array of
// the user(I presumed your objects were users, or carts maybe)
// It will now be available to the next stage of the pipeline as
// a singular object for each item in the array,
// see the picture below for how this works practically.
}
},
{
$group: {
// Now we're going to restructure the object to
// center around the id field of the products, and
// at the same time we can add up the total price
// and count of each item.
_id: '$products.id', // This is the selector for the grouping process (in our case it's the id)
item: { $first: '$$ROOT.products' }, // this is me thinking you'll want access to the item in question for each total.
totalCount: { $sum: "$products.count" }, // adds to totalCount EACH $products.count that we have
totalPrice: { $sum: { $multiply: ["$products.price", '$products.count'] } }, // self explanatory
}
}
]
this is what unwind does to your array and object
VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
NB I modified/removed some variable names(_id, oid) for practical reasons, you'll have to parse through which ones and this code will most likely not work right away if copy-pasted.
I'm currently getting data from themoviedb.com API. but I discovered the request doesn't include the specific genres for each movie. I created a separate json file that contains all the genres I need. Is there a way I can map data in my genres.json files to the remote API request?
{
"genres": [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 80,
"name": "Crime"
},
{
"id": 99,
"name": "Documentary"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 10751,
"name": "Family"
},
{
"id": 14,
"name": "Fantasy"
},
{
"id": 36,
"name": "History"
},
{
"id": 27,
"name": "Horror"
},
{
"id": 10402,
"name": "Music"
},
{
"id": 9648,
"name": "Mystery"
}
]
}
This is how you might do that.
Basically with Vue, you want to create a computed value that maps over the response from the movie API and adds the genre information to the response.
console.clear()
const genres = [
{
"id": 28,
"name": "Action"
},
{
"id": 12,
"name": "Adventure"
},
{
"id": 16,
"name": "Animation"
},
{
"id": 35,
"name": "Comedy"
},
{
"id": 80,
"name": "Crime"
},
{
"id": 99,
"name": "Documentary"
},
{
"id": 18,
"name": "Drama"
},
{
"id": 10751,
"name": "Family"
},
{
"id": 14,
"name": "Fantasy"
},
{
"id": 36,
"name": "History"
},
{
"id": 27,
"name": "Horror"
},
{
"id": 10402,
"name": "Music"
},
{
"id": 9648,
"name": "Mystery"
}
]
new Vue({
el: "#app",
data:{
genres,
movies: null
},
computed:{
moviesWithGenre(){
// if the movies haven't been populated from the AJAX response yet
// return an empty array
if (!this.movies) return []
return this.movies.map(movie => {
return {
// add all the existing movie properties
...movie,
// add the genres
genres: movie.genre_ids
// remove the genres we don't know
.filter(id => this.genres.map(g => g.id).includes(id))
// get the name
.map(id => this.genres.find(g => g.id === id).name)
}
})
}
},
created(){
var url = "https://api.themoviedb.org/3/movie/popular?api_key=8e3003c0c81633dc53b9d15ffa3399e1&language=en-US&page=1"
axios.get(url)
.then(response => this.movies = response.data.results)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<div id="app">
<ul>
<li v-for="movie in moviesWithGenre">
{{movie.original_title}}
<ul>
<li v-for="g in movie.genres">{{g}}</li>
</ul>
</li>
</ul>
</div>
I do not understand how any of this is related to vue.js as it looks like a pure javascript logic problem.
Here are some advices that could help you :
Rather than keeping an hardcoded list of Categories which is susceptible to get outdated and to break your application, i would recommend you to get them from the api itself :
https://developers.themoviedb.org/3/genres/get-movie-list
When having the result of both your genres and find request you could add the genre names to the object you are getting like so :
// Here the result of the 'genres' call
var genres = [...]
function getGenreName(genreId) {
var genre = genres.find(function(element) {
return element.id === genreId
})
if (!genre) return 'unknownGenre'
return genre.name
}
movieResults.map(function(movieResult) {
movieResult['genreNames'] = movieResult.genre_ids.map(function(genreId) {
return getGenreName(genreId)
})
return movieResult
})
Example:
const depositAddress = '2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG';
DBarray1.forEach( (tx) => {
console.log(tx);
})
TXarray2.forEach( (sim) => {
console.log(sim);
});
DBarray1 = [
{
"_id": "575e2b7875a402111900ba8f",
"username": "aleluia#gmail.com",
"playerWallet": "2NFt8YfydBU5JD9U8Xq2ucbfUp2sP7BjUrh",
"User_Profile": {
"TXHash": [
"7fbe28f75412f19dfd123a08ce03c33c302aa13d1e68d38ab8cb4c7418777f8e"
]
}
},
{
"_id": "575e2946b909906a17ea65b9",
"username": "super#user.com",
"playerWallet": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"User_Profile": {
"TXHash": [
"cf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b",
"6219def49d2e8284a6031f4c7e05e21adf756d38904e6359bd7844ae14c75a50"
]
}
}
] // end console.log(DBarray1);
TXarray2 = [
{
"id": "cf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b",
"normalizedHash": "f62af1a61c7eb569c1a171ad23c70bc218bd7244c9c5c92cf7d98638314fbbc5",
"date": "2016-06-21T04:11:18.541Z",
"fee": 6280,
"inputs": [
{
"previousHash": "2660fb761354671912b0cea6427e9ee91a98a507e5f1408865a6058b566b508c",
"previousOutputIndex": 0
},
{
"previousHash": "ce3ef138c11ea4d1766cce52ccf5f1e91790bc03b56561b0eb669041bae4e1a3",
"previousOutputIndex": 0
}
],
"outputs": [
{
"vout": 0,
"account": "2N92kApgroS6CTVuTajtjWtpcAZpUiyQoDT",
"value": 861003
},
{
"vout": 1,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 3100000,
"isMine": true,
"chain": 0,
"chainIndex": 0
}
],
"entries": [
{
"account": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"value": -3967283
},
{
"account": "2N92kApgroS6CTVuTajtjWtpcAZpUiyQoDT",
"value": 861003
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 3100000
}
],
"confirmations": 70,
"pending": false,
"instant": true,
"instantId": "5768be65427689eb06e597559c7e6cf0",
"blockhash": "00000000002d9fb51c7c3c1607fe062eff686aa6be657a59fee6c3044963897d",
"height": 872152
},
{
"id": "6219def49d2e8284a6031f4c7e05e21adf756d38904e6359bd7844ae14c75a50",
"normalizedHash": "179a4466fdfc5470e99e43aa177d43aa4f09e3a06760fd5bebffdda080d4407f",
"date": "2016-06-21T04:13:23.650Z",
"fee": 9096,
"inputs": [
{
"previousHash": "5d2879a79ea3d0dcb50049ef9ca46ef7e8d82caf2073a299a6cd0332add404c8",
"previousOutputIndex": 1
},
{
"previousHash": "d75288e69a3fc2edd534ddcd845af6a280a27af58013ae82828c8a8f813829c1",
"previousOutputIndex": 0
},
{
"previousHash": "eea4f9b274708b60c1b030203543a155857bc54aa11055ada04aceee706f96b9",
"previousOutputIndex": 0
}
],
"outputs": [
{
"vout": 0,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 2000000,
"isMine": true,
"chain": 0,
"chainIndex": 0
},
{
"vout": 1,
"account": "2MzFTm5jnCDiAapjNnyVgZAJrXMKfQ74esV",
"value": 9859
}
],
"entries": [
{
"account": "2MzcwVFKF274bMNT5tNEDY7Ua7bAgvFUdu9",
"value": -35316
},
{
"account": "2MzFTm5jnCDiAapjNnyVgZAJrXMKfQ74esV",
"value": 9859
},
{
"account": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"value": -1983639
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 2000000
}
],
"confirmations": 70,
"pending": false,
"instant": true,
"instantId": "5768bee2b5bdf3f406e7db035aef016a",
"blockhash": "00000000002d9fb51c7c3c1607fe062eff686aa6be657a59fee6c3044963897d",
"height": 872152
},
{
"id": "7fbe28f75412f19dfd123a08ce03c33c302aa13d1e68d38ab8cb4c7418777f8e",
"normalizedHash": "b4f1974dccde5ea9dfb0abcd7d4a6f3f14995d9dd422aa7d2a9078229ff18ff4",
"date": "2016-06-21T03:39:25.034Z",
"fee": 3465,
"inputs": [
{
"previousHash": "97fbb6ed8646f7ce9ed10a4230a70348151d5b6b208ad068e3a1a3fddae2dc0e",
"previousOutputIndex": 2
}
],
"outputs": [
{
"vout": 0,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 111200000,
"isMine": true,
"chain": 0,
"chainIndex": 0
},
{
"vout": 1,
"account": "2NFJnLrhsCDfG3ooQvGC169gnzBabtRgV2y",
"value": 244246993
}
],
"entries": [
{
"account": "2NCGUnwpNgaJbhMZKLJcBrWvZhWnai5PjVC",
"value": -355450458
},
{
"account": "2NFJnLrhsCDfG3ooQvGC169gnzBabtRgV2y",
"value": 244246993
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 111200000
}
],
"confirmations": 77,
"pending": false,
"instant": false,
"blockhash": "0000000000509dbc80cc3d86cdb10ce8e87ab7867c6775a9b00ca904fbe70da7",
"height": 872145
}
]// end console.log(TXarray2);
How can we check if TXarray2.id which is the transactions id, if it matches a payment made by the user inside DBarray1.User_Profile.TXHash for examplecf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b .
I want to know forEach TXarray2.id who made the payment . I tried to do this with promises and i will share some code when i get home but i'm sure it can be done with async for all users one by one and log who made a payment today to this wallet. I tried with array.find() method to check inside TXHash but failed, i don't fully grasp many prototype methods yet...
Hopefully someone already thinks this a walk on the park for him and found a better solution to validate this kind of stuff. I will accept any answer even with lodash, maping, anything. TY !!!
You iterate TXArray2 and do a lookup in DBarray1 for the transactionId.
I like to work with native array methods like map and filter, so I would use something like the following:
const result = TXarray2.map(tx => ({
transaction: tx,
user: DBarray1.filter(user => user.User_Profile.TXHash.indexOf(tx.id) > -1)[0]
}));
In this example result is an array where every element contains a transaction and the matching user.
If you already have all of the transaction and user data, could you do something like this?
// for each transaction in TXarray2
for (let { 'id': transactionId } of TXarray2) {
// check each entry in DBarray1
for (let { '_id': userId, 'User_Profile': { 'TXHash': transactions } } of DBarray1) {
if (transactions.includes(transactionId)) {
console.log(`${transactionId} was made by ${userId}`);
}
}
}
The best way here is to use Array.indexOf (or Array.findIndex if you want to use callbacks) which returns -1 if an entry is not in an array.
Here's the sync variant:
var paid = [];
TXArray2.forEach(function(transaction){
for(var i = 0; i < DBArray1.length; ++i){
if(DBArray1[i].User_Profile.TXHash.indexOf(transaction.id) > -1){
paid.push({
user : DBArray1[i],
transaction : transaction
});
break;
}
}
});
console.log(paid);