javascript-执行查询时返回未定义的对象

我正在Node.js上构建一个通过mongoose与MongoDB一起使用的应用程序.连接是完美的,我可以添加新文档,问题绝对不在连接中.

我在一个单独的.js文件中构建了与猫鼬兼容的所有功能,我从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
}

问题出在getCategory()函数中,当我在app.js(此项目的node.js项目的主文件)中调用它时,它仅返回未定义的值.而且我知道变量类别已填写,因为我插入了console.log(类别);并得到以下结果:

[ { _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");
});

每当在我的app.js中接收到变量类别时,它都会以未定义的形式到达.

有人能帮我吗?

解决方法:

您没有在快递路由器中正确使用从getCategory()返回的Promise对象:

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

相反,您可以使用async / await来帮助弥合当前同步代码与基于异步基于Promise的数据库接口之间的差距:

    app.get('/', async (req, res) => {
        var categories = await configDB.getCategory();
        res.render('home', categories);
    });
上一篇:javascript-Node Express猫鼬数组未填充参考模型


下一篇:javascript-如何使用本机节点驱动程序在节点服务器上执行mongo查询字符串?