你好,我正在尝试使用nodejs将数据保存到mongodb中,但它说:
TypeError: Cannot read property 'crud_name' of undefined at insertRecord (D:\nodejs\node_web\controllers\crudController.js:18:28) at router.post (D:\nodejs\node_web\controllers\crudController.js:12:6)
Controller :
router.get('/crud',(req, res) => {
res.render("crud", {crud : new Crud(), newCrud : true});
});
router.post('/', (req, res) => {
insertRecord(req, res);
});
function insertRecord(req, res) {
console.log(req.body);
var crud = new Crud();
crud.crud_name = req.body.crud_name;
crud.crud_email = req.body.crud_email;
crud.crud_mobile = req.body.crud_mobile;
// Save methods
crud.save((err, doc) => {
if (!err)
res.redirect('crud');
else {
console.log('Error during record insertions : ' + err);
}
});
}
架构:
var crudSchema = new mongoose.Schema({
crud_name: {
type: String
},
crud_email: {
type: String
},
crud_mobile: {
type: String
}
});
mongoose.model('Crud', crudSchema );
表格:
<form method="POST" action="/crud">
<div class="form-group">
<label for="inputAddress">Name</label>
<input type="text" name="crud_name" class="form-control" id="inputAddress" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="inputAddress">Email</label>
<input type="email" name="crud_email" class="form-control" id="inputAddress" placeholder="Enter your email">
</div>
<div class="form-group">
<label for="inputAddress">Mobile</label>
<input type="number" name="crud_mobile" class="form-control" id="inputAddress" placeholder="Enter your mobile">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
首次运行
npm 我的主体解析器
将这些添加到您的 app.js/main.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
//This will serve parsing for the whole application.
app.use(bodyParser.json());
//Rest of the code
在这里阅读有关 body-parser 的更多信息 https://www.npmjs.com/package/body-parser
我是一名优秀的程序员,十分优秀!