【问题标题】:TypeError: connection.model is not a function in mongoose-auto-incrementTypeError:connection.model 不是 mongoose-auto-increment 中的函数
【发布时间】:2018-12-13 09:02:36
【问题描述】:

我尝试连接 mongodb。但我做不到。我认为 [autoIncrement.initialize] 是问题,但我无法解决问题。这是我的代码。

const mongoose = require('mongoose');
const autoIncrement = require('mongoose-auto-increment');
require('dotenv').config();

mongoose.Promise = global.Promise;

const connect = mongoose.connect(process.env.MONGODB_URI);
autoIncrement.initialize(connect);

这是错误回溯:

/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:27
      throw ex;
      ^

TypeError: connection.model is not a function
    at Object.exports.initialize (/Users/loo/Projects/example-app/node_modules/mongoose-auto-increment/index.js:10:34)
    at Object.<anonymous> (/Users/loo/Projects/example-app/app.js:8:15)
    at Module._compile (internal/modules/cjs/loader.js:702:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
    at Module.load (internal/modules/cjs/loader.js:612:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
    at Function.Module._load (internal/modules/cjs/loader.js:543:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)

【问题讨论】:

  • 标题暗示代码不止于此。是吗?
  • @mexo 这是正常的问题。因为 mongoose-auto-increment 模块尝试访问在.initialize 方法调用中作为参数传递的.model 连接方法。事实上 LOO 应该添加错误回溯以获取更多信息。但是应该使用我的答案中的示例来解决问题。
  • @mexo 我添加了其他信息 (;

标签: node.js mongoose mongoose-auto-increment


【解决方案1】:

正如您在this link 中阅读的示例

你会看到这个:

var connection = mongoose.createConnection("mongodb://localhost/myDatabase");

autoIncrement.initialize(connection);

事实上.connect.createConnection 是不同的东西。

由于documentation here 说:

Mongoose 会在您调用时创建默认连接 mongoose.connect().

您可以使用访问默认连接 mongoose.connection.

这意味着mongoose.connect 不返回连接,您可以使用mongoose.connection 获得该连接。

解决方案:

mongoose.connect(process.env.MONGODB_URI, {useNewUrlParser: true})
        .then(() => {
          console.log('Connected to DB');
        })
        .catch(error => {
          console.error('Connection to DB Failed');
          console.error(error.message);
          process.exit(-1);
        });
autoIncrement.initialize(mongoose.connection);



或者您可以在此处创建连接:

const connection = mongoose.createConnection(process.env.MONGODB_URI);
autoIncrement.initialize(connection);

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 2016-06-24
    • 1970-01-01
    • 2022-11-21
    • 2022-12-19
    • 2018-07-03
    • 1970-01-01
    • 2019-12-30
    • 2017-05-03
    相关资源
    最近更新 更多