Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.

Explore o novo chatbot do Developer Center! O MongoDB AI chatbot pode ser acessado na parte superior da sua navegação para responder a todas as suas perguntas sobre o MongoDB .

Conecte-se a um MongoDB database usando Node.js

Lauren Schaefer5 min read • Published Feb 04, 2022 • Updated Nov 29, 2023
Facebook Icontwitter iconlinkedin icon
Classifique este início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
QuickStart Node.js Logo
Usa Node.js? Quer aprender MongoDB? Esta série de blogs é para você!
Nesta série de Início rápido, mostrarei os fundamentos de como começar a usar o MongoDB com o Node.js. Na publicação de hoje, vamos abordar como se conectar a um MongoDB database a partir de um script Node.js, recuperando uma lista de bancos de dados e imprimindo os resultados em seu console.
Esta publicação usa o MongoDB 4.4, Driver MongoDB Node.js 3.6.4 e Node.js 14.15.4.
Click here to see a previous version of this post that uses MongoDB 4.0, MongoDB Node.js Driver 3.3.2, and Node.js 10.16.3.
Prefere aprender por vídeo? Podemos ajudar você. Confira o vídeo abaixo que mostra como se conectar e como realizar as operações CRUD.

configurar

Antes de começarmos, precisamos garantir que você tenha concluído algumas etapas de pré-requisito.

Instalar o Node.js

First, make sure you have a supported version of Node.js installed. The current version of MongoDB Node.js Driver requires Node 4.x or greater. For these examples, I've used Node.js 14.15.4. See the MongoDB Compatability docs for more information on which version of Node.js is required for each version of the Node.js driver.

Instale o driver Node.js do MongoDB

O driver Node.js do MongoDB permite que você interaja facilmente com MongoDB databases dentro de aplicativos Node.js. Você precisará do driver para se conectar ao seu banco de dados e executar as queries descritas nesta série de Início rápido.
Se você não tiver o driver Node.js do MongoDB instalado, poderá instalá-lo com o seguinte comando.
1npm install mongodb
At the time of writing, this installed version 3.6.4 of the driver. Running npm list mongodb will display the currently installed driver version number. For more details on the driver and installation, see the official documentation.

Crie um MongoDB Atlas cluster gratuito e carregue os dados de amostra

Agora, você precisará de um MongoDB database. A maneira mais fácil de começar a usar o MongoDB é por meio do Atlas, o banco de dados como serviço totalmente gerenciado do MongoDB.
Head over to Atlas and create a new cluster in the free tier. At a high level, a cluster is a set of nodes where copies of your database will be stored. Once your tier is created, load the sample data. If you're not familiar with how to create a new cluster and load the sample data, check out this video tutorial from MongoDB Developer Advocate Maxime Beugnet.
Get started with an M0 cluster on Atlas today. It's free forever, and it's the easiest way to try out the steps in this blog series.

Obtenha as informações de conexão do cluster

A etapa final é preparar seu cluster para conexão.
In Atlas, navigate to your cluster and click CONNECT. The Cluster Connection Wizard will appear.
O assistente solicitará que você adicione seu endereço IP atual à lista de acesso IP e crie um usuário MongoDB, caso ainda não o tenha feito. Certifique-se de anotar o nome de usuário e a senha que você usa para o novo usuário do MongoDB, pois precisará deles em uma etapa posterior.
Next, the Wizard will prompt you to choose a connection method. Select Connect Your Application. When the Wizard prompts you to select your driver version, select Node.js and 3.6 or later. Copy the provided connection string.
For more details on how to access the Connection Wizard and complete the steps described above, see the official documentation.

Conecte-se ao seu banco de dados de um aplicativo Node.js

Agora que tudo está configurado, é hora de programar! Vamos escrever um script Node.js que se conecta ao seu banco de dados e lista os bancos de dados em seu cluster.

Importar MongoClient

The MongoDB module exports MongoClient, and that's what we'll use to connect to a MongoDB database. We can use an instance of MongoClient to connect to a cluster, access the database in that cluster, and close the connection to that cluster.
1const { MongoClient } = require('mongodb');

Criar nossa função principal

Let's create an asynchronous function named main() where we will connect to our MongoDB cluster, call functions that query our database, and disconnect from our cluster.
1async function main() {
2 // we'll add code here soon
3}
The first thing we need to do inside of main() is create a constant for our connection URI. The connection URI is the connection string you copied in Atlas in the previous section. When you paste the connection string, don't forget to update <username> and <password> to be the credentials for the user you created in the previous section. The connection string includes a <dbname> placeholder. For these examples, we'll be using the sample_airbnb database, so replace <dbname> with sample_airbnb.
Note: The username and password you provide in the connection string are NOT the same as your Atlas credentials.
1/**
2* Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
3* See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
4*/
5const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/sample_airbnb?retryWrites=true&w=majority";
Agora que temos nosso URI, podemos criar uma instância do MongoClient.
1const client = new MongoClient(uri);
Note: When you run this code, you may see DeprecationWarnings around the URL string parser and the Server Discover and Monitoring engine. If you see these warnings, you can remove them by passing options to the MongoClient. For example, you could instantiate MongoClient by calling new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true }). See the Node.js MongoDB Driver API documentation for more information on these options.
Now we're ready to use MongoClient to connect to our cluster. client.connect() will return a promise. We will use the await keyword when we call client.connect() to indicate that we should block further execution until that operation has completed.
1await client.connect();
Agora podemos interagir com nosso banco de dados. Vamos criar uma função que imprima os nomes dos bancos de dados nesse cluster. Geralmente, é útil conter essa lógica em funções bem nomeadas para melhorar a legibilidade da sua base de código. Ao longo desta série, criaremos novas funções semelhantes à função que estamos criando aqui à medida que aprendemos a escrever diferentes tipos de consultas. Por enquanto, vamos chamar uma função cujo nome é listDatabases().
1await listDatabases(client);
Let's wrap our calls to functions that interact with the database in a try/catch statement so that we handle any unexpected errors.
1try {
2 await client.connect();
3
4 await listDatabases(client);
5
6} catch (e) {
7 console.error(e);
8}
We want to be sure we close the connection to our cluster, so we'll end our try/catch with a finally statement.
1finally {
2 await client.close();
3}
Once we have our main() function written, we need to call it. Let's send the errors to the console.
1main().catch(console.error);
Putting it all together, our main() function and our call to it will look something like the following.
1async function main(){
2 /**
3 * Connection URI. Update <username>, <password>, and <your-cluster-url> to reflect your cluster.
4 * See https://docs.mongodb.com/ecosystem/drivers/node/ for more details
5 */
6 const uri = "mongodb+srv://<username>:<password>@<your-cluster-url>/sample_airbnb?retryWrites=true&w=majority";
7
8
9 const client = new MongoClient(uri);
10
11 try {
12 // Connect to the MongoDB cluster
13 await client.connect();
14
15 // Make the appropriate DB calls
16 await listDatabases(client);
17
18 } catch (e) {
19 console.error(e);
20 } finally {
21 await client.close();
22 }
23}
24
25main().catch(console.error);

Listar os bancos de dados em nosso cluster

In the previous section, we referenced the listDatabases() function. Let's implement it!
Essa função recuperará uma lista de bancos de dados em nosso cluster e imprimirá os resultados no console.
1async function listDatabases(client){
2 databasesList = await client.db().admin().listDatabases();
3
4 console.log("Databases:");
5 databasesList.databases.forEach(db => console.log(` - ${db.name}`));
6};

Salvar seu arquivo

You've been implementing a lot of code. Save your changes, and name your file something like connection.js. To see a copy of the complete file, visit the nodejs-quickstart GitHub repo.

Executar seu script Node.js

Agora você já pode testar seu código! Execute seu script aplicando um comando como o seguinte em seu terminal: node connection.js
Você verá uma saída como a seguinte:
1Databases:
2 - sample_airbnb
3 - sample_geospatial
4 - sample_mflix
5 - sample_supplies
6 - sample_training
7 - sample_weatherdata
8 - admin
9 - local

O que vem a seguir?

Hoje, você conseguiu se conectar a um MongoDB database a partir de um script Node.js, recuperar uma lista de bancos de dados em seu cluster e visualizar os resultados no console. Legal!
Now that you're connected to your database, continue on to the next post in this series where you'll learn to execute each of the CRUD (create, read, update, and delete) operations.
Enquanto isso, consulte os seguintes recursos:
Questions? Comments? We'd love to connect with you. Join the conversation on the MongoDB Community Forums.

Facebook Icontwitter iconlinkedin icon
Classifique este início rápido
star-empty
star-empty
star-empty
star-empty
star-empty
Relacionado
exemplo de código

Final Space API


Jul 07, 2022 | 1 min read
exemplo de código

Aplicação de exemplo Hostels Kenya


Jul 07, 2022 | 4 min read
Tutorial

Crie um blog moderno com Gatsby e MongoDB


Apr 02, 2024 | 16 min read
Tutorial

Criar um backend de gerenciamento de mídia escalável: integrando Node.js, Armazenamento de blobs Azure e MongoDB


Nov 05, 2024 | 10 min read