【问题标题】:Error: mongoose.model is not a function错误:mongoose.model 不是函数
【发布时间】:2023-03-21 21:02:01
【问题描述】:

我正在学习一些不同的 MEAN 教程,但我对这些教程似乎都没有遇到的问题感到困惑。我收到以下错误:

Uncaught TypeError: mongoose.model is not a function

我尝试删除 node_modules 并重新安装所有内容,但没有帮助。我错过了什么?我正在使用 Webpack 加载我的模块。这和这个问题有关系吗?

这是我的模型:

./app/authentication/user.model.js

'use strict';

var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    password: String
});

mongoose.model('User', UserSchema);

以及以下 mongoose 配置文件:

./server/config/mongoose.js

'use strict';

var config = require('./environment');
var mongoose = require('mongoose');

module.exports = function() {
    var db = mongoose.connect(config.db);

    mongoose.connection.on('error', function(err) {
        console.error('MongoDB connection error: ' + err);
        process.exit(-1);
    });

    require('../../app/authentication/user.model');

    return db;
};

【问题讨论】:

  • 你用的是什么版本的猫鼬?请注意,为您的项目安装的版本由您的项目的 package.json 管理,运行 npm install mongoose@latest 以强制使用最新版本
  • 我用的是4.4.12,是最新版本。

标签: javascript node.js mongoose webpack


【解决方案1】:

在最后添加这一行:

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

【讨论】:

  • 回调的问题用这条线
  • 我刚刚尝试过,但遗憾的是,我仍然遇到同样的错误。
  • 我正在使用 Webpack 来加载我的模块。这和这个问题有关系吗?
  • @jrsowles 你找到解决方案了吗?我有同样的问题。 stackoverflow.com/questions/41004659/…
【解决方案2】:

我降级了我的猫鼬,它运行良好:

mongoose": "^4.13.12", "mongoose-auto-increment": "^5.0.1",

【讨论】:

  • 我相当肯定我们有同样的问题,因为我在将猫鼬版本提升到 5+ 后遇到了这个问题。问题是文档之前设置的猫鼬就像let mongoose = require('mongoose').connect(config.mongoURI,config.mogoOptions);。在 5+ 中,这需要为 let mongoose = require('mongoose'); mongoose.connect(config.mongoURI,config.mogoOptions); connect 需要单独调用,因为它在 5+ 中不返回猫鼬对象。
【解决方案3】:
'use strict';

var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
    firstName:{
       type: String,
       required: true
    },
    lastName:{
       type: String,
       required: true
    },
    email:{
       type: String,
       required: true
    },
    password:{
       type: String,
       required: true
    }
});

mongoose.model('User', UserSchema);

我希望这对某人有所帮助。我花了很多时间才弄明白。

【讨论】:

    猜你喜欢
    • 2017-01-24
    • 2017-04-21
    • 1970-01-01
    • 2017-10-23
    • 2013-01-04
    • 1970-01-01
    • 2017-05-09
    • 2021-09-14
    • 2021-05-10
    相关资源
    最近更新 更多