3

I'm building an application on Node.js that works with MongoDB through mongoose. The connection is perfect, I can add new documents, the problem is definitely not in the connection.

I'm building all the functions that work with mongoose in a separate .js file, which I called from dbconfig.js.

dbconfig.js

const mongoose = require('mongoose');

// Models
const User = require('./models/User');
const Category = require('./models/Category');

var database_name = "htm";
mongoose.Promise = global.Promise;

// Connection with database_name
var connect = () => {
    mongoose.connect("mongodb://localhost/"+database_name, {useNewUrlParser: true}).then(() =>{
        console.log("Conectado ao database: " + database_name);
    }).catch((erro) => {
        console.log("Erro ao se conectar ao database: " + database_name +" - "+ erro);
    });

    mongoose.model('users', User);
    mongoose.model('categories', Category);
}

var getCategory = () => {
    const Ref = mongoose.model('categories');
    Ref.find().then((categories) => {
        return categories;
    })
}

module.exports = {
    connect: connect,
    getCategory: getCategory
}

The problem is in the getCategory () function, when I call it in my app.js (my main file of this project node.js), it returns only undefined. And I know that the variable categories are filled out because I inserted a console.log (categories); and got the following result:

[ { _id: 5c7ea6fb91526418ec3ba2fd,
    name: 'UNHAS',
    slug: 'unhas',
    __v: 0 } ]

app.js

const express = require('express');
const app = express();
const categoriesRouter = require('./routes/categories');
const handlebars = require('express-handlebars');
const path = require('path');
const configDB = require('./dbconfig')

// Config
    // Template Engine
        app.engine('handlebars', handlebars({defaultLayout: 'main'}));
        app.set('view engine', 'handlebars');

    // Start Database Connection
        configDB.connect();

    // Public
        app.use(express.static(path.join(__dirname, "public")));

// Routes
    app.use('/categorias', categoriesRouter);

    app.get('/', (req, res) => {
        var categories = configDB.getCategory();

        res.render('home', categories);

    });

app.listen(3001, () =>{
    console.log("Servidor iniciado na porta 3001");
});

Whenever the variable categories is received in my app.js it arrives as undefined.

Can someone help me?

2 Answers 2

3

You are not properly using the Promise object returned from getCategory() in your express router:

    app.get('/', (req, res) => {
        var categories = configDB.getCategory(); <-- this is a Promise, not a synchronous value
        res.render('home', categories);
    });

Instead, you can use async/await to help bridge the gap between your currently synchronous code and the asynchronous Promise-based database interface you have:

    app.get('/', async (req, res) => {
        var categories = await configDB.getCategory();
        res.render('home', categories);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

It did not work for me, but it inspired me to work with promises and solve the problem
1

Inspired by a response given by @jakemingolla who suggested async-await, I started using callback to return the 'categories' object and everything worked perfectly.

function in my file dbconfig.js

const getCategoryList = (callback) => {
    CategoryRef.find().then((categories) => {
        callback(categories);
    })
}

calling the function in my app.js file

app.get('/', (req, res) => {
    database.getCategoryHomeList((categories) => {
        res.render('home', {categories: categories});
    })
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.