A Nodejs server application gets Name and Age from an HTML form (with post method) and with the help of ExpressJS and Mongoose has to create a MongoDB document. That works but Age is not written in the document of the collection. Please help me to fix it.
Here are the files with the code: personform.html located in: C:\\Program Files\\nodejs\\myapp\\public 4.6-mongo.js in: C:\\Program Files\\nodejs\\myapp Person.js (mongoose schema and MongoDB connectio details) placed in: C:\\Program Files\\nodejs\\myapp created.ejs (ejs) in: C:\\Program Files\\nodejs\\myapp\\views MongoDB is installed in: C:\\Program Files
personform.html
<html>
<body>
<form action='/create' method='post'>
Name: <input name='name'>
<p>
Age: <input age='age'>
<p>
<input type=submit value='Submit Form!'>
</form>
</body>
</html>
4.6-mongo.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var Person = require('./Person.js');
app.use('/create', (req, res) => {
var newPerson = new Person ({
name: req.body.name,
age: req.body.age,
});
newPerson.save( (err) => {
if (err) {
res.type('html').status(500);
res.send('Error: ' + err);
}
else {
res.render('created', {person : newPerson});
}
} );
});
app.use('/public', express.static('public'));
app.use('/', (req, res) => { res.redirect('/public/personform.html'); } );
app.listen(8000, () => {
console.log('Listening on port 8000');
});
Person.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/mydatabase');
var Schema = mongoose.Schema;
var personSchema = new Schema({
name: {type: String, required: true, unique: true},
age: Number
});
module.exports = mongoose.model('Person', personSchema);
personSchema.methods.standardizeName = function() {
this.name = this.name.toLowerCase();
return this.name;
}
created.ejs
The problem is in your form and specifically your age input. It should be name="age"
<form action='/create' method='post'>
Name: <input type="text" name='name'>
<p>
Age: <input type="text" name='age'>
<p>
<input type=submit value='Submit Form!'>
</form>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.