Error: Cannot find module '../models/User' - Mongoose schema

Error: Cannot find module '../models/User' - Mongoose schema

我正在我的 Sapper 应用程序中导入一个模块,但出现错误 Cannot find module '../models/User'

导入 const User = require('../models/User');

导出为 module.exports = User = mongoose.model('user', UserSchema);

我缺少什么来完成这项工作?根据 vscode.

路径是正确的

'../models/User.js':

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  date: {
    type: Date,
    default: Date.now,
  },
});

module.exports = User = mongoose.model('user', UserSchema);

编辑: 我通过使用 npx degit "sveltejs/sapper-template#rollup" my-app.

开始一个新项目来重新创建错误

即使项目是新的,我也遇到了同样的错误,而且我还没有安装任何额外的依赖项link

路径正确,经vscode

确认

当您将鼠标悬停在 require 内的字符串上时,它将显示您正在引用的文件的绝对路径。通过 ls <path of odule>

检查它所需要的模块是否存在

我对 Sapper 没有太多经验,但据我所知,问题是实际调用是由 __sapper_/dev/server/server.js 而不是来自 src 文件夹的调用。如果您使用 const User = require('../../../models/User') 它应该可以工作,但您需要处理这个深度相对路径。

您需要将模型文件夹导出到更接近该文件的路径,或者想出一个函数来确定根路径并在需要模型时用作前缀,例如 const User = require(rootPath() + './models/User')