0

我尝试根据与 MongoDB 中的另一个集合相关的 ObjectId 显示一个集合字段。我有 3 个收藏:

用户:

{
    "_id" : "115ds1f4sd55fe1e51fds5f4",
    "name" : "Sam",
    "age" : 25
}

国家:

{
    "_id" : "654564dsf65g4d1e51fds5f4",
    "userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
    "country" : "New Zealand"
}

{
    "_id" : "8247dddsf65g4d1e51fds5f4",
    "userId" : ObjectId ("115ds1f4sd55fe1e51fds5f4"),
    "country" : "Australia"
}

地址:

{
    "_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"
}

现在在我练习的应用程序上,我使用 Swiper Slider Module 显示此用户居住的国家/地区,现在我想根据 Swiper 滑块中显示的国家/地区显示此用户在轮播下拥有的所有地址。

例如:如果滑块位于澳大利亚,则 IonCard 仅显示 1 个位于悉尼的地址。如果滑块在新西兰,IonCard 会显示奥克兰和惠灵顿的 2 个地址。

如果有人有任何想法,那就太棒了!

这是我用来在 swiper 滑块中获取国家/地区的函数:

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]);

我也想使用类似的函数来获取地址,但不确定如何从 country 函数中检索 countryId。这是我使用的:

return collection?.find({ countryId: new ObjectId("654564dsf65g4d1e51fds5f4") });

它将显示来自这个 countryId 的地址,但是当幻灯片更改为另一个国家/地区时它不会改变。

4

1 回答 1

0

我感觉您正在寻找的不仅仅是这些,如果这是真的,您能否提供更多信息

db.collection.find( { CountryId: { $eq: ObjectId("654564dsf65g4d1e51fds5f4") } } )

https://docs.mongodb.com/manual/reference/method/db.collection.find/

于 2021-11-29T20:52:55.807 回答