Every time I start a server Mongoose makes an unnecessary connection to the database

Asked

Viewed 202 times

1

Good evening, everyone!

I’m starting in the area and as a first goal I decided to create a simple e-commerce, only every time I start my server, it runs a connection to the database unnecessarily, I got the flea behind my ear, because after all, it would be safe? I don’t have to close the connection every time I make an appointment or something?

If anyone can explain me these concepts and tals, follow my code

Coloquei um console.log para exibir a mensagem

Below follows the section where I make the connection, what I wanted to know would be more a concept even, not to make silly mistakes in the future, It may even be that my question does not make much sense for experienced staff

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/didixo', {useNewUrlParser: true}).then(function(){
  console.log("Conectado a base de dados")
}).catch(function(err){
  console.log("Erro ao conectar a base de dados: " + err)
})
/questions/ask#

1 answer

1


Mongodb works different from relational database. It is advisable you NAY close the connection while using the app, only do so when it is closed.

The connection is being made because you are EXECUTING the code. Connection cannot be made if the code is not called. What you should do is placed in a different file and in the file you will use it, use require.

Mongo.js

const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost/bancodedados', { useNewUrlParser: true })
mongoose.Promise = global.Promise

module.exports = mongoose

In the file you will use (model), you do:

user js.

const mongoose = require('../mongo')

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    require: true
  },
  password: {
    type: String,
    require: true
  }
})

const User = mongoose.model('User', UserSchema)

module.exports = User

And when you need to access User, do:

const User = require('../database/models/user')

User.find({})

About not making silly mistakes, that’s normal, since you’re learning. It is like a child who learns to speak, first speaks 'mama' or 'papa' before saying 'mommy' or 'daddy'. Maybe just using an ESLINT will help you limit some common mistakes, and help you maintain a pattern throughout the project.

  • Friend, I really appreciate the tips, I have been researching about the ESLINT, because I did not know it, I will use it for sure, thank you!!

Browser other questions tagged

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