簡體   English   中英

Mongodb 查詢返回空數組,而集合中滿是記錄

[英]Mongodb query returns empty array while collection is full of records

我對 mongo db 有疑問。 我總是從充滿記錄的收集請求中得到空數組。 它以前工作但具有不同的結構,我在端點連接到數據庫。 現在重構查詢后似乎沒有返回任何記錄。 收集和數據庫 object 正確返回。

我正在使用最新的 sveltekit 和 vite

我在 $lib/mongodb/db 中的函數:

const url = MONGODB_URI;
const client = new MongoClient(url);
const dbName = 'Destinations';

export async function connectToDatabase(coll: string) {
    await client.connect();
    console.log('Succesfully connnected to the server');
    const db = client.db(dbName);
    const collection = db.collection(coll);
    return collection;
}
export async function getCountries() {
    const collection = await connectToDatabase('Countries');
    // const collection = db.collection('Countries');
    const query = await collection.find({}).toArray();

    console.log(query);

    return query;
    // .finally(() => client.close());
}

端點:

import { getCountries } from '$lib/mongodb/db';

export async function get() {
    try {
        const countriesArr = await getCountries();
        return {
            status: 200,
            body: {
                countriesArr
            }
        };
    } catch (err: any) {
        return {
            status: 500,
            body: {
                error: err.message
            }
        };
    }
}

我認為問題在 getCountries() function 中已經存在,因為 console.log(query) 已經返回空數組。

解決了,我的數據庫名稱錯誤,當我查看我的 mongodb 指南針時,我意識到了這一點。 我把它誤認為是 mongodb web 應用程序中的集群/項目名稱。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM