Mongoose无法连接到NodeJS应用程序

wlzqhblo  于 2022-10-22  发布在  Go
关注(0)|答案(1)|浏览(320)

我正在尝试将Mongoose连接到我的NodeJS环境,但它给出了一个意外错误。之前我可以用同样的命令与Mongoose连接,但几天来它给出了错误

index.js文件

import express from 'express';
import mongoose from 'mongoose'; 
import User from './User.js';

const app = express() 
const port = 5050 
const connection_url ="mongodb+srv://admin:'passwordhere'@cluster0.hcbbvuo.mongodb.net/?retryWrites=true&w=majority";

app.use(express.json())

mongoose.connect(connection_url,{
    useNewUrlParser: true, 
    useUnifiedTopology: true,
    family: 4, }) 

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

app.post('/user',(req,res)=>{
   console.log('Creating new user')   
   const u = { "name":"Yash", "email":"yash@gmail.com", "password":"yash", "wins":0,   "losses":0   }

  User.create(u,(err,data)=>{
    if(err)
    console.log(err)
    else
    console.log(data)   
  })   
})

app.listen(port,()=>{
    console.log('Listening on port :',port) })

用户模式文件

import mongoose from 'mongoose';

const User = mongoose.Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique:true },
  password: { type: String, required: true },
  wins: { type: Number,default:0},
  losses: { type: Number,default:0},
});

export default mongoose.model('User',User)

错误

/home/yash/Desktop/VS code workspace/projects/node_modules/mongoose/lib/connection.js:824
  const serverSelectionError = new ServerSelectionError();
                               ^

MongooseServerSelectionError: 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: https://docs.atlas.mongodb.com/security-whitelist/
    at NativeConnection.Connection.openUri (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/connection.js:824:32)
    at /home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/index.js:381:10
    at /home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:41:5
    at new Promise (<anonymous>)
    at promiseOrCallback (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/helpers/promiseOrCallback.js:40:10)
    at Mongoose._promiseOrCallback (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/index.js:1234:10)
    at Mongoose.connect (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/index.js:380:20)
    at file:///home/yash/Desktop/VS%20code%20workspace/projects/crisscross-backend/index.js:12:10
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0) {
  reason: TopologyDescription {
    type: 'ReplicaSetNoPrimary',
    servers: Map(3) {
      'ac-neif60o-shard-00-00.hcbbvuo.mongodb.net:27017' => ServerDescription {
        address: 'ac-neif60o-shard-00-00.hcbbvuo.mongodb.net:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 43667453,
        lastWriteDate: 0,
        error: null,
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      },
      'ac-neif60o-shard-00-01.hcbbvuo.mongodb.net:27017' => ServerDescription {
        address: 'ac-neif60o-shard-00-01.hcbbvuo.mongodb.net:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 43667454,
        lastWriteDate: 0,
        error: null,
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      },
      'ac-neif60o-shard-00-02.hcbbvuo.mongodb.net:27017' => ServerDescription {
        address: 'ac-neif60o-shard-00-02.hcbbvuo.mongodb.net:27017',
        type: 'Unknown',
        hosts: [],
        passives: [],
        arbiters: [],
        tags: {},
        minWireVersion: 0,
        maxWireVersion: 0,
        roundTripTime: -1,
        lastUpdateTime: 43667454,
        lastWriteDate: 0,
        error: null,
        topologyVersion: null,
        setName: null,
        setVersion: null,
        electionId: null,
        logicalSessionTimeoutMinutes: null,
        primary: null,
        me: null,
        '$clusterTime': null
      }
    },
    stale: false,
    compatible: true,
    heartbeatFrequencyMS: 10000,
    localThresholdMS: 15,
    setName: 'atlas-ap0orn-shard-0',
    maxElectionId: null,
    maxSetVersion: null,
    commonWireVersion: 0,
    logicalSessionTimeoutMinutes: null
  },
  code: undefined
}

几件事:
1.我在Mongoose上的网络访问中放了‘0.0.0.0/0’作为IP,所以这不是IP的问题
1.我试着把Mongoose给出的连接应用的驱动代码

const uri = "mongodb+srv://admin:<password>@cluster0.hcbbvuo.mongodb.net/?retryWrites=true&w=majority";
   const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
   client.connect(err => {
     const collection = client.db("test").collection("devices");
     // perform actions on the collection object
     client.close();
   });

而不是mongoose.Connect,它已经起作用了,但当调用POST或GET请求来创建用户或获取任何数据时,它会给出以下错误

错误

MongooseError: Operation `users.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/home/yash/Desktop/VS code workspace/projects/crisscross-backend/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:153:23)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7)
yrdbyhpb

yrdbyhpb1#

尝试从连接配置中删除useNewUrlParser: trueuseUnifiedTopology: true
从Mongoose V6+开始,这些选项已弃用,并将抛出错误。
仅尝试使用连接字符串,而不使用其他配置:

mongoose.connect(connection_url);

相关问题