What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various tutorials from YouTube, I am facing challenges in establishing a connection to MongoDB Compass. Although I have developed Schemas and Models for users, I am unable to successfully connect to the MongoDB Compass database.

To address this issue, I have installed mongoose.

My attempt so far:

const connectDb = async () => mongoose.connect("mongodb://localhost:27017/netmapper);

What steps should I take next? How can I effectively utilize the Model I created to insert data from the form into the database?

Answer №1

  • Start by creating a .env.local file at the root and saving database credentials inside
MONGO_URI=mongodb://localhost:27017/netmapper

If the above code doesn't work, change localhost to 0.0.0.0

  • Establish a connection to MongoDB

        async function connectToMongo() {
        try {
             await mongoose.connect(process.env.MONGO_URI);
             console.log("Connected to MongoDB");
           } catch (error) {
             console.error("Error connecting to MongoDB:", error);
             throw error;
            }
        };
    
    
  • Create a schema for your data

        const testSchema = new Schema({
           name: String,
           email: String
        });
    
        const Test = models.Test|| model("Test", testSchema );
    
  • Handle incoming requests and send responses by setting up an api/xyz.js file

    async function handler(req, res) {
        if (req.method === "POST") {
            const data = req.body;
    
            try {
                await connectToMongo();
                await Test.create(data);
    
                res.status(201).json({ message: "Data Inserted!" });
            } catch (error) {
                res.status(500).json({ message: "Internal Server Error" });
            }
        }
    };
    
  • Finally, submit your form data

     async function submitFormHandler(formData) {
        const response = await fetch("/api/xyz", {
          method: "POST",
          body: JSON.stringify(formData),
          headers: {
            "Content-Type": "application/json"
          }
        });
    
        const data = await response.json();
        console.log(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

React-router-sitemap lacks a definition for 'Require'

According to the official documentation here, this is how the sitemap-builder.js file should be structured: require('babel-register'); const router = require('./router').default; const Sitemap = require('../').default; ( ...

Unexpected appearance of a blue line in Material UI when the overflow attribute is included

For my React application, I've integrated Material-UI along with styled components. The strange thing is that when I use a Chrome browser to view the app, I encounter an issue that doesn't seem to happen in Firefox. The problem arises when I add ...

Is there a way to verify the authenticity of a survey depending on the types of form elements used

Creating a form in PHP with various dynamic form elements like radio buttons, text fields, and dropdowns. Seeking to validate this form using JQuery based on the question type, which is identified by the names q1, q2, etc. $(function(){ if ($(&apo ...

Switching on Closed Captions for HTML5 video while deactivating the standard video controls

I am facing two issues. Whenever I include the track tag in my video element, the default controller of the video pops up, which is causing conflicts with my custom controls. Secondly, I am unable to figure out how to turn closed captions on and off. Thi ...

What steps can I take to condense and tidy up this output into a more compact string?

Recently, I've been experimenting with Google's APIs and attempting to create a terminal command that can inform me of the distance and travel time to a particular location. However, I'm running into an issue with the current output format: ...

Tips for adjusting the size of a drawing on an HTML 5 canvas within a personalized Polymer component

In my custom Polymer element, I am looking to dynamically resize an html5 canvas when the window resize event occurs. Despite trying to utilize the window.onresize event, I encountered difficulties with accessing canvas functions. One of the functionalit ...

Troubleshooting: Unable to Remove Files in PhoneGap

I've been working on a basic app that heavily utilizes PhoneGap to test its capabilities. Currently, I'm trying to delete a file that has been downloaded within the app, but I'm encountering some issues. The majority of the code I've im ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

easy method for creating a hyperlink that triggers a "download" pop-up box

Is there a simple and efficient way to have some of my links trigger the 'save file as' prompt (similar to right-clicking) immediately after they are clicked for the first time? ...

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...

Trouble with the display:none attribute in Firefox and Chrome

<tr style="height:5px" id="TRRSHeaderTrialBar" name="TRRSHeaderTrialBar" style='display:none'> <tr id="TREmail" name="TREmail" style="height:1px;" nowrap style='display:none'> Using the code snippet above to hide the bar w ...

One common issue is being unable to target input[type=file] when multiple forms are present on a page using JavaScript

Question: I have multiple dynamic forms on a web page, each with a file input field. How can I specifically target the correct file input using $(this) in JavaScript? Here is an example of one of my forms: <form enctype="multipart/form-data" action="c ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

Making JSON function in Internet Explorer

I'm encountering an issue retrieving data from a JSON feed specifically in Internet Explorer. Here's the problem. It functions correctly in Firefox, Chrome, and Safari, but fails to alert in IE: function perform_action(data){ alert(data); } ...

Is it possible to request a GET on a server's JSON file using a specific key?

I am currently working on a project involving an auto-suggestion exercise using a JSON file located on a server. I'm not entirely clear on the web development terminology, so one requirement has me a bit confused: The requirement states: "On the keyu ...

How should one properly initiate a new object instance with embedded data using Mongoose?

Imagine you have data retrieved from an API that needs to be saved. There are a total of 4 interconnected models, A > B > C > D, with defined schemas as follows: // Schemas const A = new Schema({ username: String, password: String, B: [B.schema], } ...

Uncovering the issue: Root admin unable to view all databases in Mongo-Express

I am facing some difficulty in setting up mongo-express with my local mongodb installation. Initially, I created an admin user using the following command: db.createUser( { user: "admin", pwd: "abc123", roles:["root"] }) In ...

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...

Simulate a failed axios get request resulting in an undefined response

I'm having an issue with my Jest test mock for an axios get request, as it's returning undefined as the response. I'm not sure where I might be going wrong? Here is the component with the axios call: import {AgGridReact} from "ag-grid- ...

How can I work with numerous "Set-Cookie" fields in NextJS-getServerSideProps?

When working with getServerSideProps, I found a way to set multiple cookies on the client device. This is the code snippet that I used: https://i.stack.imgur.com/Kbv70.png ...