最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin7PV0评论

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!

Post a comment

comment list (0)

  1. No comments so far