What methods can be utilized for posting requests and storing data in MongoDB with native, Express, and body-parser?

I've been attempting to store data in a mongodb database, but nothing seems to be working no matter what I try. The initial error I encounter is linked to the req.body

Upon clicking the submit button, console.log(req.body) shows

[Object: null prototype] { name: 'John', priority: 'go to bed' }

instead of

{ name: 'John', priority: 'go to bed' }

Furthermore, I'm unsure if I'm saving the data correctly in the database due to various conflicting methods causing confusion

The code snippet in question:

db.collection.insertOne(req.body);

along with the corresponding error:

TypeError: db.createCollection is not a function

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });

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

// Connection URL
const url = "mongodb://localhost:27017";

app.listen(7000);


app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
})

app.post('/todo',urlencodedParser,function(req, res){

    MongoClient.connect(url, { useNewUrlParser: true }, function(err,db){
        if(err) throw err;
        console.log('Databese created!');
        db.collection.insertOne(req.body);
        db.close();
    });
    console.log(req.body);
});
<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        This is an index page.

        <form class="" action="/todo" method="post">
            <input type="text" name="name" placeholder="todo">
            <input type="text" name="priority" placeholder="priority">
            <button type="submit">Submit</button>
        </form>
    </body>
</html>

Answer №1

For the first issue: To properly receive JSON data as a request object, ensure you include these two lines in your code since you are sending data in JSON format

app.use(bodyParser.urlencoded({extended:true})) 
app.use(bodyParser.json()) 

Regarding the second question: Adding a new record to MongoDB database

MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("mydb");
      var myobj = { name: "Company Inc", address: "Highway 37" };
      dbo.collection("customers").insertOne(myobj, function(err, res) {
        if (err) throw err;
        console.log("1 document inserted");
        db.close();
      });
    });

Answer №2

The issue you're facing is most likely due to not indicating the specific database within your MongoDB Instance.

const url = "mongodb://localhost:27017/myDatabaseName";

By specifying the database name in the connection URL, this problem should be resolved.

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

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Show text using AJAX when the form is submitted

I'm in the process of creating a basic form with a submit button (see below). My objective is to allow users to enter text into the input box, click submit, and have the page refresh while displaying the entered text in a div element. The user's ...

What are the benefits of creating a custom request object?

Currently in the process of constructing my own PHP framework. I've noticed that some frameworks utilize objects for this task, but I'm questioning why not just directly use the POST and GET arrays. In addition, determining whether to use POST or ...

Troubleshooting the MongoDB Unique Count Problem

I am working with a collection that contains over 10 million records, here is a sample of the data: > db.LogBuff.find() { "_id" : ObjectId("578899d5d2b76f77d083f16c"), "SUBJECT" : "DD", "SYS" : "A" } { "_id" : ObjectId("578899d5d2b76f77d083f16d"), "SUB ...

Creating a message sniping command with Discord.js

I'm having trouble getting my bot to log/snipe a message when someone says 'zsnipe'. I want to make 'zsnipe' a command, but it's not working. Could you let me know what I'm doing wrong? Here is the code snippet: bo ...

The network response header shows cookies, but they do not appear in the cookies tab of the application storage

I've been struggling to set a basic cookie using express res.cookies() in my React frontend and Node.js backend application. While everything works fine on localhost, the cookies do not get set when I deploy the application on "onrender". Below is the ...

Unique string generated within database table

Looking to create a random string consisting of 8 alphanumeric characters and save it alongside my Tournament entry in the database. The challenge lies in ensuring that this code is unique within the entire table, while also being truly random (not predic ...

Convert Ajax null value to NoneType in web2py

Every time I save information on a page, an AJAX request is sent with all the necessary data to be stored in the database. The format of this data looks similar to this example: {type: "cover", title: "test", description: null, tags: null} However, when ...

What is the best way to incorporate an AppBar featuring a Back to Top button from Material UI for React into my application?

While exploring the Material UI documentation, I came across this interesting code snippet: import React from 'react'; import PropTypes from 'prop-types'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from &ap ...

It is not possible to update the content of this element using document.getElementById and storing it in a variable

Having trouble with this simple code. Looking for some assistance! <p id="p"> Test </p> <script> var p_tag = document.getElementById("p"); document.p_tag.innerHTML = "Hey"; </script> ...

Using React to retrieve data from Firebase through axios

I recently uploaded some mp3 files to my Cloud Storage on Firebase. To retrieve these files, I am utilizing axios for the necessary operations. After modifying the permissions under the "rules" tab to: allow read, write, request; I am still encou ...

`Is it possible to implement the geocode function multiple times within a single post request using npm node-geocoder?`

I've been struggling to develop a function returnCoords(par1) that allows users to input text and convert it to coordinates using the node-geocoder npm. Despite my efforts, the function returns undefined. I attempted to resolve this using async and aw ...

What could be causing my if statement to fail even though the condition is met?

I'm attempting to generate dynamic fields based on my chosen attributes. I have two array objects called addAttributes and fakeAttributes. The fakeAttributes contain the details of the selected attributes. I have a dropdown select component that displ ...

document ready function in the Microsoft AJAX client side library

The Microsoft AJAX client-side library contains various functions that imitate the server-side Page Life Cycle and conditions like if (!Page.IsPostBack). I am unsure about which client-side function corresponds to the equivalent server-side method. What is ...

Render function in Next.js did not yield anything

Recently, I came across the next.js technology and encountered an error. Can anyone help me solve this issue? What could be causing it?View image here import React from 'react' import Button from "../components/button" function HomePa ...

What is the best way to activate DOM manipulation once a partial view has been loaded in AngularJS?

What is the best approach to manipulate the DOM after a partial view loads in AngularJS? If I were using jQuery, I could utilize $(document).ready(function(){ // do stuff here } However, with Angular, specifically when working with partial views, ho ...

Unable to retrieve data from object properties despite their visibility

I am encountering issues accessing object properties, as they keep returning as undefined. I have attempted console.log(JSON.parse(this.$store.state.user.userId)); as well as console.log(JSON.parse(this.$store.state.user[0].userId)); However, when I ...

What steps can I take to troubleshoot this issue involving Django and AJAX?

Looking to pass the selected ID of an option via an AJAX request to Django 2.1, but encountering errors. As a newcomer to Django and web development, I would appreciate any help in resolving this issue. document.addEventListener('DOMContentLoaded&apos ...

Veracode Scan finds vulnerability in jQuery html method with Improper Neutralization of Script-Related HTML Tags in a Web Page error

Veracode has flagged the issue Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) within the following line of code. $('#SummaryDiv').html(data); $.ajax({ url: 'Target_URL', type: &a ...

Having trouble accessing properties of null (reading 'split'). Please provide a valid prompt

Hey there, I could really use some assistance with an issue I've encountered. Whenever I try to click on "cancel" in a prompt, I keep getting this error message: "Cannot read properties of null (reading 'split')". Basically, all I want is ...