0

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>
4
  • Do you ever call mongoose.connect()? I dont' see it in your code here, but without it (or createConnection()) you'll never talk to MongoDB via Mongoose. Commented Dec 16, 2018 at 2:23
  • client.connect is where I connect to the DB. Everything works until I submit the form, then it just keeps loading infinitely. So many old tutorials, I am having a hard time finding info. Commented Dec 16, 2018 at 2:33
  • 2
    That's not connecting mongoose, it's connecting mongodb driver. Commented Dec 16, 2018 at 2:48
  • Also, you close that connection as soon as you make it, even if it were the right one. Commented Dec 16, 2018 at 2:53

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. You are correct, I was trying to connect to the DB multiple different ways. I think the main problem I was having was with my Mongo DB Atlas setup. It was much easier to setup using mlab.com's free sandbox. I also had an issue with promises as well which you noted above, I was using the same variable name 'res' which did throw an error in the console until I changed it. Thanks for the help, I finally got this working.
0

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

1 Comment

No, it is a little different. Please don't downvote people that attempt to help, it just discourages them helping in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.