Files for nodejs settings

Asked

Viewed 57 times

3

I’m trying to make a file with the settings but not quite sure yet how to accomplish this, in this way searching various contents, I found some features where facilitates me but it would not be my case.

I thought about using global variables for this operation but observed that they would not be as viable, due to some forums I read.

I created a file and export this information to some routes where I need it. This information is for example an email from the user where he will use to receive information from the system, the user can exchange this email at any time, so I put this data inside my database in a Colection, intended only settings (I am currently using Mongodb), that is, only one document related to this configuration is saved.

In my file I use findOne to search for this document in my database and then pass this information to export, I even managed to accomplish this in a way, but it was a little "strange" to understand and understand, and wanted to know if there is a possibility to do it in a simpler way.

config.js

const mongoose = require("mongoose")
const router = require("../routes/alunos")

// Model de configuração
require("../models/Configuracao")
const Configuracao = mongoose.model("configuracoes")

const configs = []

Configuracao.findOne().lean().then(config => {
    configs.push(config)

})

module.exports = {
    configs: configs
}

Here I am basically getting my model pulled into the array and then I pass this information to the route I want

configurations.js - this would be my route

const express = require("express")
const router = express.Router()
const mongoose = require("mongoose")

const config = require("../config/config");

require("../models/Configuracao")
const Configuracao = mongoose.model("configuracoes")



router.get('/', (req, res) => {
    console.log(config.configs[0]["_id"])
    res.render('configuracoes/configuracoes')
})

This way is returned the correct ID of my document, but I think this is a little strange.

Would you have some way to accomplish that which I wish for another method?

1 answer

1


You can use async and await in this matter

config.js

const configuracoes = async () => {
    const configuracoes = await Configuracao.findOne()
    return configuracoes
}

module.exports = {
    configuracoes: configuracoes()
}

js configurations.


const config = require("../config/config");

require("../models/Configuracao")
const Configuracao = mongoose.model("configuracoes")

router.get('/', async (req, res) => {
    let configuracoes = await config.configuracoes
    console.log(configuracoes._id)
    res.render('configuracoes/configuracoes')
})

Browser other questions tagged

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