【问题标题】:Error: Cannot find module '../models/User' - Mongoose schema错误:找不到模块 '../models/User' - Mongoose 架构
【发布时间】:2020-12-22 20:51:49
【问题描述】:

我正在我的 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确认

【问题讨论】:

  • 你为什么要做module.exports = User = mongoose.model('user', UserSchema);。当你可以简单地做module.exports = mongoose.model('user', UserSchema);
  • 改编自一门课程,但并没有什么不同。我已经测试了建议的格式。
  • 好吧,如果您可以发布您的file hierarchy 的屏幕截图,那么我可以提供帮助,到目前为止似乎没有任何问题。
  • 根据 sapper 的功能,我认为问题在于您将文件放在 src 文件夹之外。如果有构建步骤,其他文件可能会被忽略。 (没用过 sapper,但我认为你可以从 package.json 中推断出很多)

标签: node.js mongodb mongoose sapper


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    当您将鼠标悬停在require 内的字符串上时,它将显示您正在引用的文件的绝对路径。通过ls <path of odule>检查它需要的模块是否存在@

    【讨论】:

    • 悬停时看到的路径会打开我尝试访问的文件。
    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2017-05-14
    • 2020-04-14
    • 2017-01-22
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多