gpt4 book ai didi

node.js - TypeError : connection. 模型不是 mongoose-auto-increment 中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:43 25 4
gpt4 key购买 nike

我尝试连接 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)

最佳答案

正如您阅读 this link 中的示例一样

你会看到这个:

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

autoIncrement.initialize(connection);

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

由于documentation here其中说:

Mongoose creates a default connection when you call mongoose.connect().

You can access the default connection using 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);

关于node.js - TypeError : connection. 模型不是 mongoose-auto-increment 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51181833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com