无法使用localhost将mongodb连接到node-express

y3bcpkx1  于 2023-10-16  发布在  Go
关注(0)|答案(3)|浏览(131)

当我尝试使用post方法将mongoDBnodejs express连接时,我只是添加了一个记录器,如果nodejs侦听mongoDB,则会显示消息数据库已连接,但我发现尽管post方法正在工作,但Mongoclient不工作,因此记录器不工作,首先,我尝试使用(MongoClient.connect("mongodb://localhost:27017),但它导致在控制台中显示(MongooseServerSelectionError: connect ECONNREFUSED ::1:27017),所以我用(MongoClient.connect('mongodb://127.0.0.1:27017')替换了localhost。现在的结果是简单地用表单输入记录控制台,但应用程序仍然不听mongoDB,请帮助我,我完全是一个初学者
这里是代码

var express = require('express');
var router = express.Router();
var MongoClient=require("mongodb").MongoClient
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
router.post('/',function(req,res,next){
  console.log(req.body);
  next
})
router.post("/submit",function(req,res) {
  console.log(req.body);

  MongoClient.connect('mongodb://127.0.0.1:27017',function(err,client){
    if(err)
      console.log('error')
    
    else
    console.log('database connected');
     client.db('bynode').collection("users").insertOne(req.body)
  })
  res.send("got it")
  
})

module.exports = router;

请帮助我,我坚持与我的学习,因为这个错误
/error/F:\new space\node_modules\mongodb\lib\sdam\topology.js:278 const timeoutError = new error_1.MongoServerSelectionError(服务器选择在${serverSelectionTimeoutMS} ms后超时,this.description); ^ MongoServerSelectionError: connect ECONNREFUSED ::1:27017 at Timeout._onTimeout (F:\new space\node_modules\mongodb\lib\sdam\topology.js:278:38) at listOnTimeout (node:internal/timers:569:17) at process.processTimers (node:internal/timers:512:7) { reason: TopologyDescription { type: 'Unknown', servers: Map(1) { 'localhost:27017' => ServerDescription { address: 'localhost:27017', type: 'Unknown', hosts: [], passives: [], arbiters: [], tags: {}, minWireVersion: 0, maxWireVersion: 0, roundTripTime: -1, lastUpdateTime: 24984871, lastWriteDate: 0, error: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (F:\new space\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket. (F:\new space\node_modules\mongodb\lib\cmap\connect.js:285:22) at Object.onceWrapper (node:events:629:26) at Socket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { [Symbol(errorLabels)]: Set(1) { 'ResetPool' }, [cause]: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 } }, 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: null, maxElectionId: null, maxSetVersion: null, commonWireVersion: 0, logicalSessionTimeoutMinutes: null }, code: undefined, [Symbol(errorLabels)]: Set(0) {}, [cause]: MongoNetworkError: connect ECONNREFUSED ::1:27017 at connectionFailureError (F:\new space\node_modules\mongodb\lib\cmap\connect.js:379:20) at Socket. (F:\new space\node_modules\mongodb\lib\cmap\connect.js:285:22) at Object.onceWrapper (node:events:629:26) at Socket.emit (node:events:514:28) at emitErrorNT (node:internal/streams/destroy:151:8) at emitErrorCloseNT (node:internal/streams/destroy:116:3) at process.processTicksAndRejections (node:internal/process/task_queues:82:21) { [Symbol(errorLabels)]: Set(1) { 'ResetPool' }, [cause]: Error: connect ECONNREFUSED ::1:27017 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16) { errno: -4078, code: 'ECONNREFUSED', syscall: 'connect', address: '::1', port: 27017 } } }
我尝试将MongoClient.connect("mongodb://localhost:27017更改为MongoClient.connect('mongodb://127.0.0.1:27017,不同的是(MongooseServerSelectionError: connect ECONNREFUSED ::1:27017)的错误消息消失了,但节点仍然没有监听mongoDB,我希望记录器会显示“数据库已连接”,并且表单输入将存储到bynode中的数据库中,因为收集用户。

omqzjyyz

omqzjyyz1#

这段代码是工作,我试过了..这个问题是由我自己发布的,我找到了答案
`

var express = require('express');
var router = express.Router();
const { MongoClient } = require('mongodb'); 
router.get('/',function(req,res,next){
  res.render('index',{title:express})
})
 
router.post('/submit', async function (req, res, next) { 
  try { 
    console.log(req.body); 
 
    const url = "mongodb://127.0.0.1:27017"; 
    const dbName = "myDb"; 
    const client = new MongoClient(url); 
 
    await client.connect(); 
 
    console.log("Connected to the database"); 
    client.db("node").collection("users").insertOne(req.body)

    res.send("got it")

 
  } catch (error) { 
    console.error("An error occurred:", error); 
    res.status(500).send("Internal Server Error"); 
  } 
});

module.exports = router;

`

ih99xse1

ih99xse12#

我认为你在连接字符串中缺少数据库的名称,你在连接字符串中提供了localhost和端口号,但你没有告诉应用程序应该连接到哪个集合。
试着把你的收藏名称放在你的字符串中,像这样,

'mongodb://127.0.0.1:27017/{your_collection_name}'

希望能成功

zte4gxcn

zte4gxcn3#

您的客户端连接应该存在于您的请求响应之外,并且您正在使用过时的回调样式语法。Mongo建议您使用ES模块,以便支持top-level await。有一个完整的教程here

import express from 'express';
import { MongoClient } from 'mongodb';

const router = express.Router();
const client = new MongoClient('mongodb://127.0.0.1:27017');
await client.connect();

router.post("/submit", async (req, res) => {
  // console.log(req.body);
  await client.db('bynode').collection("users").insertOne(req.body);
  res.send("got it")  ;
})

export { router }

相关问题