无法将 MongoDB 与 Mongoose 连接
Posted
技术标签:
【中文标题】无法将 MongoDB 与 Mongoose 连接【英文标题】:Having Trouble connecting MongoDB with Mongoose 【发布时间】:2020-05-05 10:20:54 【问题描述】:0
我正在关注 Udemy 的 MERN Stack 教程,我正在尝试将 mongodb 与 mongoose 连接起来。我配置的代码在这里:
(db.js)
const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');
const connectDB = async () =>
try
await mongoose.connect(db);
console.log('MongoDB Connect...');
catch (err)
console.error(err.message);
//Exit process with falure
process.exit(1);
;
module.exports = connectDB;
(server.js)
const express = require('express');
const connectDB = require('./config/db');
const app = express();
//connect database
connectDB();
app.get('/', (req, res) => res.send('API Running'));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port $PORT`));
(package.json)
"name": "devconnect",
"version": "1.0.0",
"description": "Social Network for Developers",
"main": "server.js",
"scripts":
"start": "node server",
"server": "nodemon server"
,
"author": "Jason Thomas",
"license": "MIT",
"dependencies":
"bcryptjs": "^2.4.3",
"config": "^3.2.5",
"express": "^4.17.1",
"express-validator": "^6.3.1",
"gravatar": "^1.8.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.8.9",
"request": "^2.88.0"
,
"devDependencies":
"concurrently": "^5.0.2",
"nodemon": "^2.0.2"
当我进入 [npm run server]这是我的错误信息
Server started on port 5000
Password contains an illegal unescaped character
[nodemon] app crashed - waiting for file changes before starting...
我无法解决这个问题,我知道这很简单,我做错了什么,我该如何解决这个问题?
最好的问候 &谢谢你
【问题讨论】:
【参考方案1】:如果你有相同的文件夹结构,你应该有一个像这样的 config/default.json,包含你从 mongoDB 集群连接设置中复制粘贴的字符串:
"mongoURI": "mongodb+srv://username:<password>@devconnector-clusterid.mongodb.net/somethingSomething?retryWrites=true",
"jwtSecret": "secret",
"githubClientId": "",
"githubSecret": ""
请务必在输入密码时删除字符 。
新课程的所有文件都在这里 - Devconnector 2.0 在课程的 older version 中是 config/keys.js 。
【讨论】:
我认为这真的有效!!!!这就是我现在得到的:Server started on port 5000 (node:7320) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option useUnifiedTopology: true to the MongoClient constructor. MongoDB Connect...
【参考方案2】:
我一开始也犯了同样的错误。在 MongoDB URI 链接中删除 '' on
【讨论】:
以上是关于无法将 MongoDB 与 Mongoose 连接的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 mongoose 将本地 mongodb 与 node.js 应用程序连接?
将 apollo 服务器与 mongodb mongoose 连接
无法使用 nestjs/mongoose 连接 mongoDB