你好,我目前正在做一个nuxt通用程序,我想用express和mongoose作为后端,从根目录下的api文件夹获取和发布数据到数据库。所以express应该作为一个api端点从nuxt利用的工作。服务器中间件 由nuxt提供。
我在api文件夹下的index.js文件是这样的。
const express = require('express');
const connectDB = require('./db');
const Message = require('./models/Message');
const Visitor = require('./models/Visitor');
// Create express router
const router = express.Router()
// Transform req & res to have the same API as express
const app = express()
router.use((req, res, next) => {
Object.setPrototypeOf(req, app.request)
Object.setPrototypeOf(res, app.response)
req.res = res
res.req = req
next()
})
// Get visitor count from db
router.get('/visitors', async (req, res) => {
const visitors = await Visitor.find({}).countDocuments();
res.json({ visitors });
});
// Send message to db
router.post('/message', async (req, res) => {
try {
// Get message body
const { name, email, telephone, message } = req.body;
//Create message & send to db
const sending = await Message.create({
name,
email,
telephone,
message,
});
res.status(201).json({
success: true,
data: sending
});
} catch (err) {
console.log(err);
}
});
});
// Export the server middleware
export default {
path: '/api',
handler: router
}
一切都很正常,直到我从model文件夹中调用mongoose模型(结构是确定的),它给出了这个错误信息。
ERROR ServerMiddleware Error: Cannot overwrite Message model once compiled.
11:59:06
at new OverwriteModelError (node_modules\mongoose\lib\error\overwriteModel.js:20:11)
at Mongoose.model (node_modules\mongoose\lib\index.js:522:13)
at Object.<anonymous> (api\models\Message.js:38:27)
i [HMR] /api (C:\Users\Desktop\js-workspace\js-nuxt-page\api\index.js)
11:59:06
谢谢你的任何提示...