最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

express - Can't connect to MongoDB with mongoose after installing package - Stack Overflow

programmeradmin3浏览0评论

I setup a MongoDB cluster using MongoDB atlas. After this I created an express app by running the npm init -y.

I then installed some packages and set the scripts. Here is my package.json:

{
  "name": "server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon src/index.js",
    "start": "node src/index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.1",
    "cors": "^2.8.5",
    "dotenv": "^16.4.5",
    "express": "^4.21.0",
    "jsonwebtoken": "^9.0.2",
    "mongoose": "^8.8.1",
    "multer": "^1.4.5-lts.1",
    "nodemon": "^3.1.7"
  }
}

After setting this up I managed to connect to MongoDB using mongoose.

Then I ran npm i axios and I got the following error when I ran npm run dev:

Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: /

At this moment I have enabled allow access from anywhere on my MongoDB cluster. So I do not know what is happening.

Here is my index.js:

require('dotenv').config();

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

app.use(express.json())

app.use(cors({
    origin: '*',
    credentials: true
}));

app.use(bodyParser.json());

mongoose.connect(process.env.MONGODB_URI);

mongoose.connection.on('connected', () => {
    console.log('Connected to MongoDB');
})

mongoose.connection.on('error', (err) => {
    console.log('Error connecting to MongoDB', err);
});

app.get('/', (req, res) => {
    res.send('API');
});

app.listen(process.env.PORT, () => {
    console.log(`API listening at http://localhost:${process.env.PORT}`);
});

module.exports = app;

I tried testing this with other packages too, but it happens everytime I install ANY package.

Any help would be appreciated!

发布评论

评论列表(0)

  1. 暂无评论