Michael Benson
Michael Benson

Reputation: 75

How to get a mongodb query to frontend code

I'm trying to query a MongoDB database and then display it to the frontend code/page.

Here's what I got so far. Note, it does sucessfully console.log() the search results on the backend just not on the frontend.

Backend File

export async function searching() {
    let output = "";
    const mongo = require('mongodb').MongoClient
    const url = "mongodb+srv://[protected..]";
    await mongo.connect(url, {useNewUrlParser: true,useUnifiedTopology: true}, (err, client) => {       
        const db = client.db('domains')
        const collection = db.collection('domains')
        collection.find().toArray((err_again, items) => {
            output = items
            console.log(output)
            return output
        })
    })
}

Frontend

export async function button2_click(event) {
    let output = await searching()
    console.log(output)
}

Note I'm doing this in Wix code so some of the synctax front-end syntax might be different.

The "console.log(output)" gets an undefined response.

When I console log the backend file the "console.log(output)" successfully outputs the array, but it's now showing on the frontend console.

Please help I've been spending hours on this with no luck. THANK YOU!

Upvotes: 0

Views: 1317

Answers (1)

Michael Benson
Michael Benson

Reputation: 75

I was able to figure this out so I figured I would post the answer here:

export async function findRecord(database, sub_db, query) {
    let output = "";
    const mongo = require('mongodb').MongoClient
    const url = "mongodb+srv://...";
    const client = await mongo.connect(url, {useNewUrlParser: true,useUnifiedTopology: true});

    const db = client.db(database)
    const collection = db.collection(sub_db)
    const items = await collection.find(query).toArray();
    client.close()
    return items;
}

Upvotes: 1

Related Questions