I try to show one collection field based on the ObjectId that's related to another collection in MongoDB. I have 3 collections:
Users:
{
"_id" : "115ds1f4sd55fe1e51fds5f4",
"name" : "Sam",
"age" : 25
}
Country:
{
"_id" : "654564dsf65g4d1e51fds5f4",
"userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
"country" : "New Zealand"
}
{
"_id" : "8247dddsf65g4d1e51fds5f4",
"userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
"country" : "Australia"
}
Address:
{
"_id" : "6184s68f4se65f4se6d545ee",
"CountryId" : ObjectId("654564dsf65g4d1e51fds5f4"),
"userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
"address" : "12345 Main Street",
"city" : "Auckaland"
}
{
"_id" : "6184s68f4se65f4se6d545ee",
"CountryId" : ObjectId("654564dsf65g4d1e51fds5f4"),
"userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
"address" : "12345 Main Street",
"city" : "Wellington"
}
{
"_id" : "6184s68f4se65f4se6d545ee",
"CountryId" : ObjectId("8247dddsf65g4d1e51fds5f4"),
"userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
"address" : "12345 Main Street",
"city" : "Sydney"
}
Now on the app that I practice on, I use Swiper Slider Module to display the Country this user lived, now I want to show all the Addresses this user has under the carousel depending on which country is displayed in the Swiper slider.
For example: If the slider is in Australia, the IonCard only show 1 address in Sydney. If the slider is in New Zealand, the IonCard shows 2 addresses of Auckland & Wellington.
If anyone has any idea that will be awesome!
Here is the function that I use to fetch the country in the swiper slider:
useEffect(() => {
async function fetchCountry() {
const client = app.currentUser?.mongoClient("mongodb-atlas");
const collection = client?.db("database").collection("country");
return collection?.find({ userId: new ObjectId(app.currentUser?.id) });
}
if (loadingCountry) {
fetchCountry().then((r) => {
setCountry(r);
setLoadingCountry(false);
});
}
}, [loadingCountry]);
And I want to use a similar function to fetch the address as well but not sure how I can retrieve the countryId from the country function. Here is what I used:
return collection?.find({ countryId: new ObjectId("654564dsf65g4d1e51fds5f4") });
it will show the address from this countryId however it won't change when the slides change to another country.