Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning undefined object when doing a query

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?

like image 234
Francisco Alisson Avatar asked Sep 22 '26 18:09

Francisco Alisson


2 Answers

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);
    });
like image 184
jakemingolla Avatar answered Sep 24 '26 08:09

jakemingolla


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});
    })
});
like image 45
Francisco Alisson Avatar answered Sep 24 '26 07:09

Francisco Alisson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!