【问题标题】:node.js on express unable to find the model快递上的node.js找不到模型
【发布时间】:2017-10-22 00:32:24
【问题描述】:

我的路由器文件中有一个 post 方法,我从 Contact 模型中实例化了一个对象。但是我对 Contact 模型没有定义。错误是

错误:

**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
   }

models/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);

【问题讨论】:

    标签: node.js express mongoose mean-stack


    【解决方案1】:

    您的模型是正确的。您必须使用 body-parser 来解析请求正文。

    见:

    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())
    

    【讨论】:

      猜你喜欢
      • 2013-06-14
      • 1970-01-01
      • 2017-09-27
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 2011-07-14
      • 1970-01-01
      相关资源
      最近更新 更多