我的路由器文件中有一个post方法,我从Contact模型中实例化了一个对象。但我对Contact模型的定义不明确。错误是
错误:
**TypeError: Cannot read property 'firstname' of undefined**
路由/ contact.js
var express = require('express');
var router = express.Router();
var Contact = require("../models/contacts");
router.post('/contact', function(req, res, next) {
res.send("POST method");
newContact = new Contact({
firstname: req.body.firstname,
lastname: req.body.lastname
}
模型/ contacts.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var contactSchema = new Schema({
firstname: String,
lastname: String
});
var Contact = module.exports = mongoose.model('Contact', contactSchema);
答案 0 :(得分:1)
你的模型是正确的。您必须使用正文解析器来解析请求正文。
见:
https://www.npmjs.com/package/body-parser#examples
在routes / contact.js
中添加以下代码var bodyParser = require('body-parser')
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())