如何在node/express server配置mongoDB [duplicate]

new9mtju  于 2023-04-20  发布在  Go
关注(0)|答案(1)|浏览(132)

此问题已在此处有答案

Can't connect to MongoDB 6.0 Server locally using Nodejs driver(1个答案)
5天前关闭。
我尝试在我的本地主机上运行一个使用MongoDB作为数据库的Node/Express服务器。我以前从未使用过MongoDB,所以我按照mongo文档安装了MongoDB和Mongosh。
安装后,我在默认端口27017上运行mongo服务器(mongod)和mongo客户端(mongosh),没有问题。
mongod控制台消息:

...
    {"t":{"$date":"2023-04-13T16:58:08.218-03:00"},"s":"I",  "c":"NETWORK",  "id":23015,   "ctx":"listener","msg":"Listening on","attr":{"address":"127.0.0.1"}}
    {"t":{"$date":"2023-04-13T16:58:08.218-03:00"},"s":"I",  "c":"NETWORK",  "id":23016,   "ctx":"listener","msg":"Waiting for connections","attr":{"port":27017,"ssl":"off"}}
...

mongosh控制台消息:

...
Current Mongosh Log ID: 64385f4e504e549f2d810293
Connecting to:          mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.8.0
Using MongoDB:          6.0.5
Using Mongosh:          1.8.0
...

当我尝试使用npm start运行服务器时,它应该在我的本地主机上创建一个db,但我得到以下错误:

Listening on port 4000
Caught exception: {"message":"connect ECONNREFUSED ::1:27017","reason":{"type":"Single","setName":null,"maxSetVersion":null,"maxElectionId":null,"servers":{},"stale":false,"compatible":true,"compatibilityError":null,"logicalSessionTimeoutMinutes":null,"heartbeatFrequencyMS":10000,"localThresholdMS":15,"commonWireVersion":null}}

我很确定mongo的服务器和客户端都已经在运行了,所以我不知道为什么我会得到连接ECONNREFUSED错误。欢迎任何帮助

更新一:添加代码

config/default.json:

{
  "apiVersion": "v1.1",
  "entorno": "default",
  "mongodb": {
      "uri": "mongodb://localhost:27017/challenge_v1_db"
  },
  "apiKeys": {
    "localhost": "35cfafab8ef7cfcb2a9bc4e8e4303f59"
  }
}

fakeData.js:

import Products from '@/models/Products.model';
import Deliveries from '@/models/Deliveries.model';
import faker from 'faker';

const productsQuantity = 2000;
const deliveriesQuantity = 100000;

const buildProducts = async () => {
  let total = await Products.countDocuments();
  if (total > productsQuantity) {
    console.log('fake Products data ready');
    return;
  }

  let data = [];
  for (let i = 0; i < productsQuantity; i++) {
    let fakeData = {
      reference: faker.commerce.productName(),
      description: faker.commerce.productDescription(),
      weight: faker.datatype.number(),
      height: faker.datatype.number(),
    };
    data.push(Products.create(fakeData))
  };

  await Promise.all(data);
}

const buildDeliveries = async () => {
  let total = await Deliveries.countDocuments();
  if (total > deliveriesQuantity) {
    console.log('fake Deliveries data ready');
    return;
  }
  let data = [];
  for (let i = 0; i < deliveriesQuantity; i++) {
    let random = faker.datatype.number();
    let productsFromDb = await Products.find().limit(random > 6 ? 6 : random);

    let products = [];
    for (let product of productsFromDb) {
      products.push(product._id);
    }
    let fakeData = {
      when: faker.date.soon(),
      origin: {
        street: faker.address.streetName(),
        number: faker.datatype.number(),
        postalCode: faker.address.zipCode(),
        city: faker.address.city(),
      },
      destination: {
        street: faker.address.streetName(),
        number: faker.datatype.number(),
        postalCode: faker.address.zipCode(),
        city: faker.address.city(),
      },
      products,
    };

    data.push(Deliveries.create(fakeData))
  };

  await Promise.all(data);
}

export default {
  buildProducts,
  buildDeliveries
}

app.js:

import bodyParser from 'body-parser';
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import config from 'config';
import fakeData from './config/fakeData';

require('mongoose-schema-jsonschema')(mongoose);

const app = express();
app.use(cors());
app.use(bodyParser.json({limit: '25mb'}));
app.use(bodyParser.urlencoded({
  extended: true
}));

mongoose.Promise = global.Promise;

mongoose.connect(config.get('mongodb.uri'), {
  useNewUrlParser: true,
  connectTimeoutMS: 2147483647,
  useUnifiedTopology: true
});
mongoose.connection.on('error', (err) => {
  throw err;
});
mongoose.connection.on('connected', async () => {
  console.log('MongoDB database connected! Environment:', config.get('entorno'));
  try {
    await fakeData.buildProducts();
    await fakeData.buildDeliveries();
  } catch (e) {
    console.log('MongoDB ensuring indexes FAIL', e);
  }
});

// Routes
import router from './components/router/routes';
router.mountRoutes(app);

// Handle uncaughtException
process.on('uncaughtException', (err) => {
  console.log('Caught exception: %j', err);
});

export default app;
6ljaweal

6ljaweal1#

看起来问题可能与使用IPv6(::1)而不是IPv4(127.0.0.1)的连接有关。尝试更改您的配置:

{
  "apiVersion": "v1.1",
  "entorno": "default",
  "mongodb": {
      "uri": "mongodb://127.0.0.1:27017/challenge_v1_db"
  },
  "apiKeys": {
    "localhost": "35cfafab8ef7cfcb2a9bc4e8e4303f59"
  }
}

此外,您可以添加一个选项到mongoose.connect()调用中,以帮助调试问题:

mongoose.connect(config.get('mongodb.uri'), {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverSelectionTimeoutMS: 5000,
  socketTimeoutMS: 45000,
  family: 4
});

相关问题