javascriptmongodbexpresspostbody-parser

How do you use mongodb native, express and body-parser to post request and save data?


I have been trying to save data to a mongodb database but nothing I do seems to work. the first error i'm getting is related to the req.body

When I click the submit button, console.log(req.body) returns

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

rather than

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

Secondly, I don't know if I'm saving the data to the database correctly because I have seen so many different ways of doing it that I'm confused

The relevant line of code

db.collection.insertOne(req.body);

and relevant 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>
        I am 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>


Solution

  • Regarding first error, You should add this two line to get json data as a request object because you're sending data in json

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

    Regarding second query: Inserting record in mongoDB

    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();
          });
        });