Mongodb connection with nodejs

Asked

Viewed 3,010 times

0

How do I connect to the Mongo database with nodejs? I’ve looked at several sites but I’m not getting it right! I thank those who help!

2 answers

3

Use the Mongoosis.

Here’s an example of how to open the connection

var mongoose = require('mongoose');
global.db = mongoose.connect('mongodb://localhost:27017/neventos');
mongoose.connection.on('connected', function () {
 console.log('=====Conexão estabelecida com sucesso=====');
});
mongoose.connection.on('error', function (err) {
 console.log('=====Ocorreu um erro: ' + err);
});
mongoose.connection.on('disconnected', function () {
 console.log('=====Conexão finalizada=====');
}); 

In that link has a complete design that I used Mongoose to make the connection.

  • Do I need anything other than installing mongodb and nodejs? It is that it gives error in the console saying "require is not defined"

  • Node.js is a language used for server side, by the error you said is occurring, it is probably calling this js file in a browser, hence the implementation is different, you will have to use something like requirejs in your project.

  • And you have to install Mongoose too.

  • But it is necessarily the Mongoose to establish the connection to db?

1

You can perform as follows:

require('dotenv').config();
const { MongoClient } = require('mongodb');


class MyConnect extends MongoClient {

  constructor(url, options) {
    super(url, options);
    this.client = null;

    this.on('insert-value', this.insertValue)
  }

async insertValue(data) {
    try {
       this.client = await this.connect()

       const collection = this.client.db('testando').collection('olhaai');
       const response = await collection.insertOne(data);

       console.log(response);
       this.client.close();
     } catch (error) {
        console.log(error);
     }
  }
}

(new MyConnect(
    process.env.MONGOURL, 
    { 
        useNewUrlParser: true, 
        useUnifiedTopology: true 
    })
).emit('insert-value', { ola: 'fion', tudo: 'bom'});

Remembering that the Mongocliente class inherits from the Eventemitter class so you can use the:

module.exports = MyConnect;

with this you can use your class office and call the event listeners that are within it with the . Emit('Eventname', options);

good use.

inserir a descrição da imagem aqui I did the test 4 times, you can manipulate the querys by the event listener, or calling the function itself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.