MERN堆栈-找不到模块-module.exports=mongoose.model



我正在学习这篇MERN堆栈教程,并从第7分钟开始观看这段关于模型和模式的视频:https://www.youtube.com/watch?v=O8IipcpTmYU&list=PL4cUxeGkcC9iJ_KkrkBZWZRHVwnzLIoUE&索引=5

我用mongoose创建了一个模式,并导出了它,当需要它时,在我的路由文件中找不到它。

文件结构:

MERN
| client/
| models/
|  - workoutModel.js
| server/
|  - node_modules/
|  - routes/
|  -- workouts.js
|  - .env
|  - package-lock.json
|  - package.json
|  - server.js

训练.js

const express = require('express');
const router = express.Router();
const Workout = require('../models/workoutModel.js');
// /api/workouts/
// GET all workouts
router.get('/', (req, res) => {
res.json({msg: 'GET all workouts'})
})
// GET single workout
router.get('/:id', (req, res) => {
res.json({msg: 'GET single workout'})
})
// POST new workout
router.post('/', async (req, res) => {

})
// DELETE a workout
router.delete('/:id', (req, res) => {
res.json({msg: 'DELETE a workout'})
})
// UPDATE a workout
router.patch('/:id', (req, res) => {
res.json({msg: 'UPDATE a workout'})
})
module.exports = router;

workoutModel.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const workoutSchema = new Schema({
title: {
type: String,
required: true
},
reps: {
type: Number,
required: true
},
load: {
type: Number,
required: true
}
}, { timestamps: true });
module.exports = mongoose.model('Workout', workoutSchema);

这是我的错误:

throw err;
^
Error: Cannot find module '../models/workoutModel.js'
Require stack:
- C:UsersUSERDocumentsMERNserverroutesworkouts.js
- C:UsersUSERDocumentsMERNserverserver.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:UsersUSERDocumentsMERNserverroutesworkouts.js:3:17)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:UsersUSERDocumentsMERNserverserver.js:11:23)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\Users\USER\Documents\MERN\server\routes\workouts.js',
'C:\Users\USER\Documents\MERN\server\server.js'
]
}

我逐字逐句地遵循了教程,我不知道哪里出了问题!感谢您的帮助。

也许这个代码会像这个

const Workout = require('../../models/workoutModel.js');

你应该再次检查文件路径

你能用这行试试吗?

const Workout = require('../models/workoutModel');

相关内容

  • 没有找到相关文章

最新更新