express上的node.js找不到模型
在我的路由器文件中有一个post方法,我在其中实例化了联系人模型中的一个对象。但我对联系人模型的定义不明确。错误是 错误:express上的node.js找不到模型,node.js,express,mongoose,mean-stack,Node.js,Express,Mongoose,Mean Stack,在我的路由器文件中有一个post方法,我在其中实例化了联系人模型中的一个对象。但我对联系人模型的定义不明确。错误是 错误: **TypeError: Cannot read property 'firstname' of undefined** routes/contact.js var express = require('express'); var router = express.Router(); var Contact = require("../models/contacts"
**TypeError: Cannot read property 'firstname' of undefined**
routes/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
}
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var contactSchema = new Schema({
firstname: String,
lastname: String
});
var Contact = module.exports = mongoose.model('Contact', contactSchema);
models/contacts.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
}
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var contactSchema = new Schema({
firstname: String,
lastname: String
});
var Contact = module.exports = mongoose.model('Contact', contactSchema);
你的模型是正确的。您必须使用主体解析器来解析请求主体 见: 在routes/contact.js中添加以下代码
var bodyParser = require('body-parser')
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())