首页 > 解决方案 > Mongoose MongoNetworkError // 连接错误

问题描述

我与猫鼬的连接有问题。我正在尝试连接到 mongoDB 地图集并获取 MongoNetworkError。

那是我的代码和错误日志。谢谢你的帮助。

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser =require('body-parser');
const mongoose = require('mongoose');

const productRoutes = require('./api/routes/products');
const ordersRoutes = require('./api/routes/orders');

mongoose.connect('mongodb://robertRobot:robertRobot@nodeshop-shard-00-00-5oqzt.mongodb.net:27017,nodeshop-shard-00-01-5oqzt.mongodb.net:27017,nodeshop-shard-00-02-5oqzt.mongodb.net:27017/test?ssl=true&replicaSet=NodeShop-shard-0&authSource=admin&retryWrites=true',
    { useNewUrlParser: true }
    ).then().catch(err=>{
        console.log('xxxxxxxxxxxxxxxxxxxxxx');
        console.log(err);
    });

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended : false}));
app.use(bodyParser.json());

app.use((req,re,next)=>{
    res.header('access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Autorisation');


if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow', 'PUT, POST, PATCH, DELETE, GET');
    return res.status(200).json({});
    next();
}

});

app.use('/products', productRoutes);
app.use('/orders', ordersRoutes);

app.use((req, res,next)=>{
    const error = new Error('not found');
    error.status = 404;

    next(error);
});

app.use((error, req, res, next)=>{
    res.status(error.status || 500);
    res.json({
        error: {
            message : '500 error'
        }
    });

});

module.exports = app;

错误日志:

    { MongoNetworkError: connection 4 to nodeshop-shard-00-02-5oqzt.mongodb.net:27017 closed
    at TLSSocket.<anonymous> (/Users/robertas/Desktop/node-js/restApi/node_modules/mongodb-core/lib/connection/connection.js:276:9)
    at Object.onceWrapper (events.js:315:30)
    at emitOne (events.js:121:20)
    at TLSSocket.emit (events.js:211:7)
    at _handle.close (net.js:561:12)
    at TCP.done [as _onclose] (_tls_wrap.js:360:7)
  name: 'MongoNetworkError',
  errorLabels: [ 'TransientTransactionError' ],
  [Symbol(mongoErrorContextSymbol)]: {} }

标签: javascriptnode.jsmongodbmongoose

解决方案


重新启动您的 MongoDB。如果使用 Linux,请尝试以下命令:

sudo service mongod start

另外,只需在 mongo shell 中提供 mongo 并检查它是否正常工作。


推荐阅读