node.js 类型错误:无法解构“未定义”或“空”的属性“db”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49921816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:46:38  来源:igfitidea点击:

TypeError: Cannot destructure property `db` of 'undefined' or 'null'

node.jsmongodbtypeerrorvardestructuring

提问by Demesew Abebe

I am getting a TypeError in my variable assignment for mongodb connection. Is there a workaround for this?

我在 mongodb 连接的变量赋值中遇到 TypeError。有解决方法吗?

//server.js
var mongoose = require('mongoose');
var config = require('./config');

var { db: {user,pass,host,port,name } } = config;

var connectionString = `mongodb://${user}:${pass}@${host}:${port}/${name}`;

mongoose.connect(connectionString, { useMongoClient: true });

Error

错误

C:\mean\webguidv1\server.js:65
  db: {
  ^

TypeError: Cannot destructure property `db` of 'undefined' or 'null'.

Here is my config.js file

这是我的 config.js 文件

// config.js
var env = process.env.NODE_ENV; // 'dev' or 'test'

var dev = { app: { port: 3000 }, db: {user: '', pass: '', host: '', port: , name: '' }};

var test = { app: { port: 3000 }, db: {user: '', pass: '', host: '', port: , name: '' }};

var config = { dev, test };

module.exports = config[env];

回答by Sawtaytoes

You're trying to deconstruct configwhere configis undefinedor null. In this case, I'm thinking it's undefined.

您正在尝试解构configwhere configisundefinednull。在这种情况下,我认为它是undefined.

If you console.log(require('./config')), you'll probably get undefined.

如果你console.log(require('./config')),你可能会得到undefined

This error also appears if you try to deconstruct an object in function args in Node 10.7.0.

如果您尝试在 Node 10.7.0 中的函数 args 中解构对象,也会出现此错误。