一、背景
在开发koa后端项目中使用mongodb数据库,并且安装mongoose操作数据库,在连接数据库,并且save document时,遇到连接报错以及数据操作报错问题。
二、问题
2.1 问题1
MongoDB connection error: MongoServerError: Authentication failed.
at Connection.sendCommand (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connection.ts:525:17)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Connection.command (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connection.ts:597:22)
at async executeScram (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/auth/scram.ts:113:20)
at async ScramSHA256.auth (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/auth/scram.ts:60:12)
at async performInitialHandshake (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connect.ts:163:7)
at async connect (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connect.ts:43:5) {
errorResponse: {
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed'
},
ok: 0,
code: 18,
codeName: 'AuthenticationFailed',
connectionGeneration: 0,
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}

2.2 问题2
MongoParseError: credentials must be an object with 'username' and 'password' properties
三、解决问题
以上2个问题,其实是一个问题,主要原因在于使用mongoose连接数据库时,数据库的user、password没有正确设置的问题。
mongoose正确使用的官方网址是:https://mongoosejs.com/
但是官方网站上给出的示例,极其简单,并没有针对mongoosede的不同版本说明对应的配置,导致很多人容易设置错误,stack overflow上也有特别多的人提出相同的issue。
以下是官方给出的示例:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));
在实际的开发中,mongodb和其他数据库一样,都有用户名和密码。所以一定会有authority的配置。
下面我给出我项目中对应版本的代码,供大家参考。
- mongoose版本:
"mongoose": "^8.8.1"
- 代码:
const url = `mongodb://@127.0.0.1:27017/dbName`; // dbName是你新的mongodb database名称
mongoose
.connect(url, {
authSource: "admin",
user: Env_Mongodb_Username, // 这里设置mongodb的username
pass: Env_Mongodb_Password, // 这里设置mongodb的password
})
.then(async () => {
console.log("Connected to MongoDB");
})
.catch((err) => {
console.error("MongoDB connection error:", err);
process.exit(1);
});
希望对大家有帮助。koa项目分享,目前已经分享了两篇内容,后续我会继续进行分享。
欢迎大家关注“新卫网络科技”微信公众号。