简体   繁体   English

当我将 mongo db 连接到 nodejs 时出现错误

[英]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); ```const timeoutError = new error_1.MongoServerSelectionError( Server selection timed out after ${serverSelectionTimeoutMS} ms ,this.description); .MongoServerSelectionError: connect ECONNREFUSED::1:27017 .MongoServerSelectionError:连接 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将 uri 更改为

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

This happened probably because the MongoDB service isn't started.发生这种情况可能是因为MongoDB服务未启动。

Follow the below steps to start it:请按照以下步骤启动它:

  1. Go to Control Panel and click on Administrative Tools. Go 到控制面板,然后单击管理工具。 (in Windows the path will be: Control Panel\System and Security\Administrative Tools ) (在 Windows 路径将是: Control Panel\System and Security\Administrative Tools
  2. Double click on Services .双击服务 A new window opens up.打开一个新的 window。
  3. Search MongoDB.exe .搜索MongoDB.exe Right click on it and select Start .右键单击它和 select开始

The server will start.服务器将启动。 Now execute npm start again and the code might work this time.现在再次执行npm start ,这次代码可能会工作。

The answer from a similar question (I can't comment so I post as an answer)类似问题的答案(我不能评论所以我发布作为答案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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