[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"$fZmK0TloKjIcE51W1JazxPlbi8XJlWbkI_93RRTAwd7c":3},{"code":4,"message":5,"data":6},200,"成功",{"id":7,"createdAt":8,"title":9,"content":10,"summary":11,"image":12,"uid":13,"user":14,"categoryId":21,"category":22,"subCategoryId":24,"subCategory":25,"comments":27,"status":17,"reason":28,"notice":28,"visitCount":29,"commentCount":30,"keywords":31},138,"2024-11-24T07:10:08.316Z","mongodb数据库的mongoose操作","## 一、背景\n在开发koa后端项目中使用mongodb数据库，并且安装mongoose操作数据库，在连接数据库，并且save document时，遇到连接报错以及数据操作报错问题。\n\n## 二、问题\n### 2.1 问题1\n> MongoDB connection error: MongoServerError: Authentication failed.\n    at Connection.sendCommand (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connection.ts:525:17)\n    at processTicksAndRejections (node:internal/process/task_queues:95:5)\n    at async Connection.command (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connection.ts:597:22)\n    at async executeScram (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/auth/scram.ts:113:20)\n    at async ScramSHA256.auth (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/auth/scram.ts:60:12)\n    at async performInitialHandshake (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connect.ts:163:7)\n    at async connect (/Users/hanweixing/Desktop/xinwei/lottery/backend/lottery-backend/node_modules/mongodb/src/cmap/connect.ts:43:5) {\n  errorResponse: {\n    ok: 0,\n    errmsg: 'Authentication failed.',\n    code: 18,\n    codeName: 'AuthenticationFailed'\n  },\n  ok: 0,\n  code: 18,\n  codeName: 'AuthenticationFailed',\n  connectionGeneration: 0,\n  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }\n}\n\n![mongodb error](https://image.xinwei.ltd/11732431368761.png)\n\n\n### 2.2 问题2\n> MongoParseError: credentials must be an object with 'username' and 'password' properties\n\n## 三、解决问题\n以上2个问题，其实是一个问题，主要原因在于使用mongoose连接数据库时，数据库的user、password没有正确设置的问题。\n\nmongoose正确使用的官方网址是：[https://mongoosejs.com/](https://mongoosejs.com/)\n\n但是官方网站上给出的示例，极其简单，并没有针对mongoosede的不同版本说明对应的配置，导致很多人容易设置错误，stack overflow上也有特别多的人提出相同的issue。\n\n以下是官方给出的示例：\n```js\nconst mongoose = require('mongoose');\nmongoose.connect('mongodb://127.0.0.1:27017/test');\n\nconst Cat = mongoose.model('Cat', { name: String });\n\nconst kitty = new Cat({ name: 'Zildjian' });\nkitty.save().then(() => console.log('meow'));\n```\n在实际的开发中，mongodb和其他数据库一样，都有用户名和密码。所以一定会有authority的配置。\n\n下面我给出我项目中对应版本的代码，供大家参考。\n- mongoose版本：\n```package.json\n\"mongoose\": \"^8.8.1\"\n```\n- 代码：\n```js\nconst url = `mongodb://@127.0.0.1:27017/dbName`; // dbName是你新的mongodb database名称\n  mongoose\n    .connect(url, {\n      authSource: \"admin\",\n      user: Env_Mongodb_Username, // 这里设置mongodb的username\n      pass: Env_Mongodb_Password, // 这里设置mongodb的password\n    })\n    .then(async () => {\n      console.log(\"Connected to MongoDB\");\n    })\n    .catch((err) => {\n      console.error(\"MongoDB connection error:\", err);\n      process.exit(1);\n    });\n```\n\n希望对大家有帮助。koa项目分享，目前已经分享了两篇内容，后续我会继续进行分享。\n\n欢迎大家关注“新卫网络科技”微信公众号。\n\n\n","koa项目，使用mongodb数据库，正确的使用mongoose进行验证连接的操作。","https://image.xinwei.ltd/11732431368761.png",499668042977349,{"phone":15,"userId":13,"nickName":16,"vipType":17,"avatar":18,"sign":19,"createdAt":20},"13121171998","全栈老韩",1,"https://image.xinwei.ltd/images/IMG_5430.JPG","全栈工程师，擅长iOS App开发、前端（vue、react、nuxt、小程序&Taro）开发、Flutter、React Native、后端（midwayjs、golang、express、koa）开发、docker容器、seo优化等。","2024-01-01T16:14:30.305Z",2,{"id":21,"name":23},"IT技术",29,{"id":24,"name":26,"parentId":21},"后端",[],"",255,0,"koa mongodb,koa mongoose,mongodb mongoose,mongodb database,mongoose connect, MongoServerError,Authentication failed,mongodb数据库,mongoose数据库连接"]