Skip to content
Advertisement

How can I return the results of my backend Query onto my frontend to display on a page

simple query

var MongoClient = require('mongodb').MongoClient;

var input = "ito";
var regexInput = new RegExp(input);

//I have removed the url and db name for privacy purposes
MongoClient.connect('', function(err, db) {
  if (err) throw err;
  var dbo = db.db("");
  var query = { brand_name: regexInput };
  dbo.collection("snacks").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

I am currently trying to learn about the MERN stack and developing an application. This is my simple query where I am just searching for snacks with “orit” substring and thus return snacks with “Doritos” etc. How may I integrate this query or take the result and display it on a page on my frontend. Or perhaps there’s a possible way to do everything completely on the frontend?

frontend page

import React, { Component } from 'react';
import styles from "./styles.module.css";

export default class SnackSearch extends Component {
    render() {

        return (
            <div>
                <h1 className = {styles.h1}>Search for your snack</h1>
                
            </div>
        )
    }

}

This is my simple frontend if necessary. I would also like to ask for how I can implement the reverse as well, where I get a user input and send it to my backend as the variable “input” and returning the result once again. I hope I do not come off as asking for a direct answer/solution for my simple problem. I do not mind if any sort of hint/guidance or resource/video is given instead so that I can learn myself. I have attempted to research use of axios and ajax but I am unsure of how to apply these two.

Advertisement

Answer

Since server and client are two different environments, you’ll have to transfer the data that you get from the database, from the server to the client.

You can do this using an express endpoint using res.send(myData). The endpoint can be responsible for calling the database.

On the client you will have to call that endpoint to request the data. Then you can use this data to display it in your react page. React official documentation has a clear example for fetching data.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement