我与猫鼬的连接有问题。 我正在尝试连接到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)]: {} }
答案 0 :(得分:0)
重新启动mongodb。如果使用linux,则try是命令: sudo服务mongod start
此外,只需将mongo装在mongo壳中,然后检查其工作即可。
答案 1 :(得分:0)
您需要在Atlas MongoDB中为网络访问输入IP 0.0.0.0/0。这意味着每个人都可以连接到您的数据库