简体   繁体   中英

got and error when i connect mongo db to nodejs

```const timeoutError = new error_1.MongoServerSelectionError( Server selection timed out after ${serverSelectionTimeoutMS} ms , this.description); .MongoServerSelectionError: connect ECONNREFUSED::1:27017

const {MongoClient}=require('mongodb');

const url='mongodb://localhost:27017/';

const client= new MongoClient(url);

const dataBase= 'nodejs';

async function getdata(){
    
    let result= await client.connect(); 
     console.log('connect to server')
    let db= result.db(dataBase)
    console.log('2')
    let collection = db.collection('node');
    let response= await collection.find({}).toArray();
    console.log(response)
}

getdata();

Change uri to

const url='mongodb://0.0.0.0:27017/';

This happened probably because the MongoDB service isn't started.

Follow the below steps to start it:

  1. Go to Control Panel and click on Administrative Tools. (in Windows the path will be: Control Panel\System and Security\Administrative Tools )
  2. Double click on Services . A new window opens up.
  3. Search MongoDB.exe . Right click on it and select Start .

The server will start. Now execute npm start again and the code might work this time.

The answer from a similar question (I can't comment so I post as an answer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM