Reputation: 141
Hi all I am having a rather strange issue. I have verified I am able to establish a connection to MongoDB, that my post action is routing from my html form to express, and that my model and schema look correct. When I fill out and try to submit the form the webpage hangs forever and does nothing. I have verified the IP is whitelisted, the connection user has full permissions, and that I could create the collection by hand via the mongo shell. I am stuck.
Here are my versions:
MongoDB: 3.4 on Atlas.
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.15.5",
"express-session": "^1.15.6",
"mongodb": "^3.0.1",
"mongoose": "^5.0.0-rc1",
"morgan": "~1.9.0",
"pug": "2.0.0-beta11",
My flow is html form > express router > model.save() for mongodb. Here are the source files I am using:
router.js
var express = require('express');
var router = express.Router();
var Post = require('../models/post.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'xxx' });
});
router.post('/', function(req, res){
var postData = new Post(req.body)
console.log(postData);
postData.save(function(err) {
if (err) throw err;
console.log('Author successfully saved.');
});
});
module.exports = router;
post.js
var url = "mongodb://admin:[email protected]:27017,xxx.mongodb.net:27017,xxx.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin";
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
var Schema = mongoose.Schema;
// create a schema
var postSchema = new Schema({
title: String,
company: String,
email: String,
desc: String,
tags: String,
created: {
type: Date,
default: Date.now
}
});
// the schema is useless so far
// we need to create a model using it
var Post = mongoose.model('Post', postSchema);
// make this available to our users in our Node applications
module.exports = Post;
Log output from container:
[0mPOST / [0m- [0m- ms - -[0m
{ created: 2018-01-04T14:43:49.755Z,
_id: 5a4e3da5890164111d2ad4ee,
title: 'I am good',
company: '1900',
desc: 'Jjj',
email: '[email protected]',
tags: 'Kkkkk' }
Upvotes: 2
Views: 1239
Reputation: 8351
This is from express doc:
The methods on the response object (res) in the following table can send a response to the client, and terminate the request-response cycle. If none of these methods are called from a route handler, the client request will be left hanging.
that's mean you need to render something to the client in order to end request/response cycle:
router.post('/', function(req, res){
var postData = new Post(req.body);
postData.save(function(err) {
if (err) throw err;
res.end('Author successfully saved.');
});
});
Upvotes: 2