0

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!

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.