我正在学习如何将MongoDB与node.js结合使用,因此我将RESTful API作为实践。
但是,每当我尝试连接到mongo图集时,我都会不断收到“ MongoNetworkError:getaddrinfo ENOTFOUND”。
我在server.js
处的代码:
// call the packages
var bodyParser = require('body-parser');
var Bear = require('./app/models/bear');
var mongoose = require('mongoose');
var express = require('express');
var app = express();
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://<userName>:<pasword>@cluster0-<someCharacters>.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect( err => {
console.log(err);
//const collection = client.db("test").collection("devices");
client.close();
});
/*rest of the code is commented out*/
...
它记录以下错误:
{ MongoNetworkError: failed to connect to server [cluster0-<someCharacters>.mongodb.net:27017] on first connect [MongoNetworkError: getaddrinfo ENOTFOUND cluster0-<someCharacters>.mongodb.net cluster0-<someCharacters>.mongodb.net:27017]
at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (/app/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at makeConnection (/app/node_modules/mongodb-core/lib/connection/connect.js:39:11)
at callback (/app/node_modules/mongodb-core/lib/connection/connect.js:261:5)
at Socket.err (/app/node_modules/mongodb-core/lib/connection/connect.js:286:7)
at Object.onceWrapper (events.js:286:20)
at Socket.emit (events.js:198:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
注释:
<userName>
,<pasword>
,<someCharacters>
相应地代表字符localhost
上正常工作我可能做错了什么?
答案 0 :(得分:1)
u已安装mongoose,但您正尝试连接mongodb软件包。因为你安装了猫鼬
const mongoUri="your connection string here"
mongoose.connect(mongoUri,{useNewUrlParser:true})
.catch((e)=>{
console.log(e.message)
process.exit(1)
})
.then(()=>{
console.log("connected to Mongo Atlas")
})
mongoose.connect返回承诺。如果有错误,连接将被拒绝,它将记录错误,然后退出该过程。如果连接成功,则意味着承诺已解决,因此它将进行连接,然后记录“已连接到Mongo Atlas”
但是,我建议您检查连接字符串。它应该有“ + srv”,像这样
mongodb+srv://