Mongoose не работает с hapi.js (простая настройка) - PullRequest
1 голос
/ 02 апреля 2019

Я экспериментирую с hapi.js и хочу подключить хапи к мангусте.но всякий раз, когда я иду по маршруту, он говорит: Internal Server Error

быстрая настройка:

моя файловая структура такова: (я не включил в задачу не связанные вещи)

/app.js
/node_modules
/models
    /Product.js
/routes
    /product-page
         /product.js
/views
    /product
         /product.html

внутри моего app.js вот как.

const Hapi = require('hapi');

const routes = require('./routes');
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/hapidb', { useNewUrlParser: true })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.error(err));



const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});


const init = async () => {

    await server.start();
    console.log(`Server running at: ${server.info.uri}`);

    // Home Route
    server.route(routes);

    await server.register(require('vision'));

    server.views({
        engines: {
            html: require('handlebars')
        },
        relativeTo: __dirname,
        path: 'views',
        partialsPath: 'views/partials'
    });


};

process.on('unhandledRejection', (err) => {

    console.log(err);
    process.exit(1);
});

init();

, как вы можете видеть, mongoose.connect работает, и когда я набираю node app.js в терминале, MongoDB connected... получаетвывод.

Теперь я создал models/Product.js для схемы, и это схема:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var ProductSchema = new Schema({
    name: String
});
module.exports = mongoose.model('Product', ProductSchema);

и теперь в моем файле маршрутов product.js.Это настройка:

    const Product = require('../../model/Product')


module.exports = [
    {
        method: 'GET',
        path: '/product',
        handler: (request, h) => {
             //something is not working here
            Product.find(function(error, product) {
                if (error) {
                    console.error(error);
                }

                return h.view('product/product.html')
            })
        }
    }
]

Теперь я попытался перейти на http://localhost:3000/product, но когда я туда иду, он говорит:

{
"statusCode": 500,
"error": "Internal Server Error",
"message": "An internal server error occurred"
}

и внутри терминала это Debug: internal, implementation, error Error: handler method did not return a value, a promise, or throw an error

Что я сделал:

Я иду к своему терминалу и набираю mongo и show dbs, я заметил, что базы данных hapidb здесь нет, поэтому яподумал может быть в этом проблема.Поэтому я пошел и набрал use hapidb и db.products.insert({name: "Television"})

Я попытался перезапустить node app.js и перейти к http://localhost:3000/product.Все еще не работает.

Теперь я попытался немного изменить свой обработчик маршрута на этот

 handler: (request, h) => {
                //I added an empty object to find all product
        Product.find({}, function(error, product) {
            if (error) {
                console.error(error);
            }

            return h.view('product/product.html')
        })
    }

Это все, что я могу придумать.Если я только вернусь return h.view('product/product.html') Это работает.но с Product.find в коде, это не работает.

Пожалуйста, помогите

1 Ответ

2 голосов
/ 02 апреля 2019

Попробуйте вернуть Product.find примерно так:

handler: (request, h) => {
    return Product.find({}, function(error, product) { // <-- This line
        if (error) {
            console.error(error);
        }

        return h.view('product/product.html')
    })
}
...