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>