繁体   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