【问题标题】:fastify-mongoose doesn't work, node.js and fastifyfastify-mongoose 不起作用,node.js 和 fastify
【发布时间】:2021-11-02 08:15:26
【问题描述】:
const ejs = require('ejs')
const path = require('path');
const fastify = require('fastify')();
const fastify_static = require('fastify-static');
const fastify_autoload = require('fastify-autoload');
const fastify_mongoose = require('fastify-mongoose');
const fastify_env = require('fastify-env');

let PORT;
let uri;

fastify.register(fastify_env, {
    dotenv: true,
    schema: {
        type: 'object',
        required: ['MONGO_URI', 'PORT'],
        properties: {
            MONGO_URI: {
                type: 'string',
                default: ''
            },
            PORT: {
                type: 'string',
                default: ''
            }
        }
    }
}).ready(err => {
    if (err) {
        throw new Error(err);
    }
    PORT = fastify.config.PORT;
    uri = fastify.config.MONGO_URI;
})

fastify.register(fastify_static, {
    root: path.join(__dirname, 'public'),
})

fastify.register(require('point-of-view'), {
    engine: {
        ejs: ejs,
    },
    root: path.join(__dirname, 'view')
})

fastify.register(fastify_autoload, {
    dir: path.join(__dirname, 'Logic/Routes'),
})

fastify.register(require('./Logic/Plugins/cache'))

fastify.register(fastify_mongoose, {
    uri: uri
})

const start = async () => {
    try {
        await fastify.ready();
        await fastify.listen(process.env.PORT);
        console.log('Listening on port: ', PORT);
    } catch (error) {
        throw new Error(error);
    }
}

start();

错误:错误:uri 参数是必需的 在 D:\Users\Antonio\Desktop\Antonio\Work\GitHub\NextLevel\src\main.js:30:15

问题出在 fastify-mongoose,或者可能是 fastify-env。我解释一下:如果我在 URI 参数中直接写 URI,它就可以工作。但是使用环境变量没有..

【问题讨论】:

    标签: javascript node.js mongoose loading fastify


    【解决方案1】:

    您是否使用 dotenv,因为您应该使用,我不建议您在代码中输入密码或访问您的 API。

    require('dotenv').config()
    

    让我们记住我们开始的时候

     start()
    

    我们启动 fastify 并且必须调用 dotenv,否则不会包含 process.env.YOUR_VARIABLE

    【讨论】:

    • 一个好的答案将始终包括解释为什么这会解决问题,以便 OP 和任何未来的读者可以从中学习。
    • 欢迎来到 Stack Overflow!我建议不要在答案中使用修辞问题。他们冒着被误解为根本不是答案的风险。您正在尝试回答此页面顶部的问题,不是吗?否则请删除此帖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 2022-01-18
    • 2022-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多