首页 > 解决方案 > 添加猫鼬模式模型来表达导致错误500

问题描述

我有通过 axios 将数据存储到猫鼬服务器的反应应用程序。在我想为不同的数据添加额外的模式之前,它工作得很好。我的模式模型是分开的,所以我想只添加另一个名为PartyList.js的模型。

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// Define collection and schema for Items
var PartyList = new Schema({
  name: {
    type: String
  },
  song_id: {
    type: String
  },
  port: {
      type: Number
  }
},{
    collection: 'party'
});

module.exports = mongoose.model('PartyList', PartyList);

这是我的 app.js 中的代码。

const config = require('./database/DB');
const ServerPortRouter = require('./routes/ServerPortRoutes');

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.use('/serverport', ServerPortRouter);

这就是我导入它并尝试运行它的方式(称为 ServerPortRoutes.js)。在运行使用此路由的应用程序的一部分后,我得到一个 50 0 (Internal Server Error)。我的服务器告诉我ReferenceError: PartyList is not defined上面定义了 3 行。

const ServerPort = require('../models/ServerPort');
const PartyList = require('../models/PartyList');

ServerPortRouter.route('/add-party').post(function (req, res) {
  const PartyList = new PartyList(req.body);
  PartyList.save()
    .then(PartyList => {
        res.json('Server added successfully');
    })
    .catch(err => {
    res.status(500).send("unable to save to database");
    });
});

标签: expressmongoose

解决方案


问题似乎是您正在重新定义 const 。在您的路线更改为const partyList = new PartyList(req.body);然后partyList用作您的变量


推荐阅读