Kustom
Kustom

Reputation: 181

How to make a post request to mongo db atlas using node.js and express.js

I am trying to make a simple post request to Mongo Db Atlas using Node.js, Express.js and Mongoose.js. I fill out the form and send the request but it just keeps loading, no erros, nothing. ANyone have any ideas?

//Require assets
const express = require('express');
const app = express();
const mongoose = require('mongoose');
let port = 3000;

const bodyParser = require('body-parser');

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

const MongoClient = require('mongodb').MongoClient;
const uri = 'mongodb+srv://michael:<PASSWORD-GOES-HERE>@around-town-vsisv.mongodb.net/admin';
const client = new MongoClient(uri, { useNewUrlParser: true });

client.connect(err => {
    const collection = client.db('around_town_db').collection('events');
   // perform actions on the collection object
    client.close();
});

mongoose.Promise = global.Promise;

var eventSchema = mongoose.Schema({
    eventName: String,
})

var eventData = mongoose.model('Event', eventSchema);

//Load index page using endpoint
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

//Post using endpoint
app.post('/addevent', (req, res) => {
    var userData = {
       eventName: req.body.eventName 
    }
    new eventData(userData)
    .save()
   .then(res => {
     res.send('item saved to database');
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

//Listen on port 3000
app.listen(port, () => {
 console.log('Server listening on port ' + port);
});

Below is a simple form for submitting the post request. Any ideas on what I am missing?

<!DOCTYPE html>
<html>
 <head>
 <title>Add a local event</title>
 </head>

 <body>
 <div class="app">
    <h1>Add an event</h1>
    <form method="post" action="/addevent">
    <label>Enter event Name</label><br>
    <input type="text" name="eventName" placeholder="Enter event name..." required>
    <input type="submit" value="Add Event">
    </form>
 </div>
 </body>
</html>

Upvotes: 0

Views: 1535

Answers (2)

Paul
Paul

Reputation: 36339

OK, so it looks like you have two problems. First, you're not letting Mongoose itself connect to your database, and second you're overwriting the response variable. If you note your .then() callback in the userData.save() promise chain, you're calling that result variable 'res' as well as the response variable 'res' from the route callback.

To fix the first problem, somewhere in your app startup, one time call (instead of your current MongoClient code)

mongoose.connect(uri)

You can also use mongoose.createConnection() if you want more fine-grained control over the connection, or need to make multiple connections to different databases.

Second problem, your post handler should look like this:

//Post using endpoint
app.post('/addevent', (req, res) => {
    var userData = {
       eventName: req.body.eventName 
    }
    new eventData(userData)
    .save()
   .then(result => { // note the use of a different variable name
     res.send(result); // also, you generally want to send *something* down that lets the user know what was saved.  Maybe not the whole object, but this is illustrative and the client will at least need to know something (e.g. the id) to refer to the object by in the future. 
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

Unrelated to your problem, but most folks write Express APIs in a RESTful manner. If you want to follow that convention, then your routes should look more like this:

GET /events              // list the events
GET /events/:eventId     // get a single event by ID
POST /events             // add a new event
PUT /events/:eventId     // update an existing event
DELETE /events/:eventId  // remove an event

Upvotes: 2

Jitendra
Jitendra

Reputation: 3185

Try something like follow:

app.post('/addevent', (req, res) => {
    var userData = new eventData({
       eventName: req.body.eventName 
    })

   userData.save()
   .then(res => {
     res.send('item saved to database');
   })
   .catch(err => {
     res.status(400).send('unable to save to database');
   });
});

Upvotes: 0

Related Questions