简体   繁体   English

Mongodb 查询返回空数组,而集合中满是记录

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

I have a problem with mongo db.我对 mongo db 有疑问。 I'm always getting empty array from my collection request full of records.我总是从充满记录的收集请求中得到空数组。 It worked previously but with different structure where I was connecting to database at endpoints.它以前工作但具有不同的结构,我在端点连接到数据库。 Now after refactoring queries don't seem to return any records.现在重构查询后似乎没有返回任何记录。 Collection and db object is returned properly.收集和数据库 object 正确返回。

I'm using latest sveltekit with vite我正在使用最新的 sveltekit 和 vite

My functions in $lib/mongodb/db:我在 $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());
}

Endpoint:端点:

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
            }
        };
    }
}

I think that the problem is arleady in getCountries() function because there console.log(query) already returns empty array.我认为问题在 getCountries() function 中已经存在,因为 console.log(query) 已经返回空数组。

Solved it, I had wrong database name, when I looked at my mongodb compass I realized this.解决了,我的数据库名称错误,当我查看我的 mongodb 指南针时,我意识到了这一点。 I have mistaken it with cluster/project name in mongodb web app.我把它误认为是 mongodb web 应用程序中的集群/项目名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM