如何将NodeJ连接到Atlas mongodb集群

时间:2019-03-29 03:14:57

标签: javascript node.js mongodb

我正在使用带有节点的Atlas数据库来设置新应用,而我得到的只是一个错误,提示“ MongoError:必须在调用MongoClient.prototype.db之前连接MongoClient”。

const uri = "mongodb+srv://alberto:pass@lel-kicis.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("students")
   .then(db => console.log('DB conectada'))
   .catch(err => console.log(error));
 });

3 个答案:

答案 0 :(得分:0)

您缺少启动mongo客户的机会。

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://alberto:pass@lel-kicis.mongodb.net/test";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("students")
   .then(db => console.log('DB conectada'))
   .catch(err => console.log(error));
 });

此外,Atlas还会为您生成初始连接代码块。请执行以下步骤。

点击连接按钮

enter image description here

从下一个窗口中选择“连接您的应用程序”

enter image description here

在下一个窗口中,选择NodeJs作为驱动程序,然后选择所需的版本。另外,选择完整驱动程序示例以获取完整代码块

enter image description here

现在复制代码并直接使用。

答案 1 :(得分:0)

如果您查看mongodb连接器文档,则MongoClient的语法为new MongoClient(url, options, callback)。回调的签名为(err, client) => { //body }

如果不传递可选的回调,则将获得MongoClient的实例(此处就是这种情况)。 connect方法还期望使用相同的回调签名,因此您的连接应类似于:

const instance = new MongoClient(uri, { useNewUrlParser: true });
// notice 'client' in the callback
instance.connect((err, client) => {
  if (err) console.log('failed to connect')
  else {
    console.log('connected')
    const collection = client.db("test").collection("students")
    ...
  }
 });

mongodb连接器还支持promise,因此您也可以这样做:

// connection is a promise
const connection = instance.connect()
connection.then((err, client) => { // etc })

答案 2 :(得分:0)

使用猫鼬和mongodb-uri:

这是初始化连接的方式:

const mongoose = require('mongoose')
const uriUtil = require('mongodb-uri')

// Create a new connection
mongoose.Promise = global.Promise
// mongoose.set('debug', DEBUG)

const dbURI = uriUtil.formatMongoose(process.env.MONGO_URI)

const options = {
    autoIndex: DEBUG,
    autoReconnect: true,
    useNewUrlParser: true
}  

const conn = mongoose.createConnection(dbURI, options)

conn.on('open', () => console.log('DB connection open'))
conn.on('error', err => console.log(`DB connection error : ${err.message}`, err))
conn.on('close', () => console.log('DB connection closed'))

module.exports = conn

使用mongoDb为驱动程序node.js 3.0或更高版本提供的连接字符串。