简体   繁体   中英

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?

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);
    });

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});
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM