Utilizing the power of Koa.js in conjunction with MongoDb for seamless development

Having an issue, or maybe just lacking some knowledge here. The question is pretty straightforward - I have this code:

router.get('/', (ctx, next) => {
    MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) {
    if (err) throw err;
        let dbo = db.db("mydb");
        let query = {address: "Highway 37"};
        dbo.collection("customers").find(query).toArray((err, result) => {
            if (err) throw err;
            console.log(result)
            db.close();
        });
    });
    ctx.body = 'END OF FILE!!!';
});

The line console.log(result) prints my data and I need to respond with this data in ctx.body. Unfortunately, I'm struggling to figure out how to get the result into my ctx.body. I've tried creating a variable like let a and setting it equal to result, but I haven't had any luck so far.

Any help would be greatly appreciated. Thanks a lot! (^_^)

Answer №1

This is how your handler might appear:

router.get('/', context => {
  MongoClient.connect(..., (error, database) => {
    ...
    db.collection("customers").find(query).toArray((error, data) => {
      context.body = JSON.stringify(data)
    })
  })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I fetch data from a ManyToMany jointable using Typeorm?

Is there a way to retrieve the categories associated with posts when fetching user data? Data Models: @Entity() export class Category extends BaseEntity { @PrimaryGeneratedColumn() id: string; @Column() name: string; @Column() description: s ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

What is the best way to share Discord conversations on the server?

I've been on a quest for quite some time to figure out how I can send a discord message to my website. After stumbling upon Express, I'm struggling to wrap my head around how to display the data on my site when a discord message event is triggere ...

Ending or stopping based on data retrieved from an ajax call

Currently, I have a php script that includes an image which, upon clicking, redirects the user to a different page. Additionally, there is an ajax/jQuery function in place to check if the user is logged in or not. When the user clicks on the link, the aja ...

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

Unable to retrieve the value from the selected radio button

Below is the provided HTML: <form> <div class="form-group"> <div class="checkbox-detailed male_input"> <input type="radio" name="gender" id="male" value="male"> <label for="male"> ...

Utilizing imported components to set state in React

In my project, I created a functional component named Age and imported it into another functional component called Signup. This was done in order to dynamically display different divs on a single page based on the authentication status of the user. By sett ...

Using JavaScript within HTML documents

Need help with inserting JavaScript code from Google: <script type='text/javascript'> googletag.cmd.push(function() { googletag.display('div-gpt-ad-1362706866260-0'); }); </script> into existing JavaScript / HTML code: va ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...

Only submit the form if all files are selected to prevent any missing files from being uploaded

I am currently utilizing the Vue.js framework along with Axios. Within my HTML page, I have incorporated two separate input fields for selecting an image. Additionally, there is a form present on the page. It's important to note that these inputs and ...

Emberjs 1.0: Data Changes don't Refresh Computed Property and Template

In my Ember.js application, I am using a datepicker which is integrated for selecting dates. When a date is clicked on the datepicker, a computed property should compare the selected date with the dates available in the timeslot to check for a match. Based ...

Display and conceal box using AngularJS checkboxes

I am currently facing some challenges in managing checkboxes and containers. The main objective is to have a list of checkboxes that are pre-selected. Each checkbox corresponds to a specific container, and when the checkbox is checked or unchecked, it shou ...

Deliver acquired post information to HTML using the read file technique

I've been diving into the world of nodeJS, jquery-mobile, and HTML5. Below is a snippet of my code: Fetching post data from an html form: req.addListener("data", function(postDataChunk){ postData += postDataChunk; console.log("Received POST ...

Encountering difficulty in accessing game.html following button clicks

Why isn't the redirection to game.html happening after clicking on the buttons in index.html? The file structure consists of server/server.js, public/index.html,public/game.html. <!DOCTYPE html> <html> <title>QUIZ GAME</title ...

Creating a dynamic user interface with HTML and JavaScript to display user input on the screen

I'm currently working on creating an input box that allows users to type text, which will then appear on the screen when submitted. I feel like I'm close to getting it right, but there's a problem - the text flashes on the screen briefly bef ...

Troubleshooting NodeJS's access denied problem on AWS S3

Here is the bucket policy that I have set up: { "Version": "2012-10-17", "Statement": [ { "Sid": "AddCannedAcl", "Effect": "Allow", &q ...

Executing the command "npm config set ignore-scripts false" will disable the enforcement of NPM security measures

Exploring ways to protect against potentially harmful npm packages, I stumbled upon a suggestion to use npm config set ignore-scripts false. But after implementing this command, I noticed that it caused issues with running other necessary commands like n ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

Issue with React event hierarchy

How can I effectively manage state changes in a deep node that also need to be handled by a parent node? Let me explain my scenario: <Table> <Row prop={user1}> <Column prop={user1_col1} /> <Column prop={user1_col2} /> ...