简体   繁体   中英

Mongodb query returns empty array while collection is full of records

I have a problem with 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.

I'm using latest sveltekit with vite

My functions in $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.

Solved it, I had wrong database name, when I looked at my mongodb compass I realized this. I have mistaken it with cluster/project name in mongodb web app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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