Express路由器无法识别猫鼬模型

时间:2018-10-12 21:46:06

标签: javascript node.js express mongoose routing

我正在开发一个node.js应用,每次运行此代码时,它会弹出一个参考错误,指出未定义Post。当我将发布路线放入app.js而不是Submit.js时,它可以正常工作。这使我相信这是因为Submit.js没有“看到” app.js中定义的模型。我对Web开发非常陌生,因此可能缺少了一些非常基本的东西。

app.js

var express = require('express');
var mongoose = require('mongoose');

var submitRouter = require('./routes/submit');
var app = express();

mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/posts");

//Mongoose Schema
var postSchema = new mongoose.Schema({
  username: String,
  date: Date,
  title: String,
  link: String,
  text: String,
  votes: Number,
  community: String
});
var Post = mongoose.model("Post", postSchema);

app.use('/submit', submitRouter);

module.exports = app;

submit.js

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');

router.post('/', function(req, res, next){
    var newPost = new Post(req.body);
    newPost.save()
      .then(item => {
      res.json(newPost);
      })
      .catch(err => {
        res.status(400).send("unable to save to database");
      });
});

module.exports = router;

1 个答案:

答案 0 :(得分:1)

帖子未定义这是因为您没有像在App.js中那样在commit.js中定义猫鼬模式。

您正在使用新的帖子创建要发布的实例,但是submit.js中不存在该帖子

我建议您将架构放在单独的文件中,然后将其导入Submit.js

创建一个名为schema的文件夹,并在该文件夹内创建一个名为PostSchema.js的文件名

PostSchema.js

   var mongoose = require('mongoose');
   //Mongoose Schema
   var postSchema = new mongoose.Schema({
       username: String,
       date: Date,
       title: String,
       link: String,
       text: String,
       votes: Number,
       community: String
   });
   var Post = mongoose.model("Post", postSchema);
   module.exports = Post;

在commit.js中导入帖子架构

  var express = require('express');
  var router = express.Router();
  var mongoose = require('mongoose');
  var Post = require('./schema/PostSchema.js');
  router.post('/', function(req, res, next){
      var newPost = new Post(req.body);
      newPost.save()
           .then(item => {
               res.json(newPost);
       })
       .catch(err => {
          res.status(400).send("unable to save to database");
       });
 });

 module.exports = router;

顺便说一下,这与Express Router无关。