【问题标题】:TypeError: Cannot destructure property `db` of 'undefined' or 'null'TypeError:无法解构“未定义”或“空”的属性“db”
【发布时间】:2018-09-30 00:01:09
【问题描述】:

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

错误

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

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

这是我的 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];

【问题讨论】:

  • 请添加./config.js文件导出
  • config 未定义或为空。错误很明显。
  • @Moti Korets 我刚刚将我的 config.js 文件添加到帖子中。我是否遗漏了此文件中的任何内容?
  • 在导出前运行console.log(env),确保它是正确的。
  • 我试过 console.log(env)。我遇到了同样的错误。

标签: node.js mongodb typeerror var destructuring


【解决方案1】:

您正在尝试解构config,其中configundefinednull。在这种情况下,我认为是undefined

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

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

【讨论】:

  • 那有什么解决办法呢?
  • 确保您导入的文件存在。
【解决方案2】:

你必须在其中使用bodyParser提到json格式,

app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));

【讨论】:

  • 与此无关,不是请求
  • 不是这个问题,我也遇到了同样的错误,错过了bodyparser的编码
猜你喜欢
  • 2021-03-21
  • 1970-01-01
  • 2020-01-21
  • 2020-05-28
  • 1970-01-01
  • 2021-03-01
  • 1970-01-01
  • 2019-07-15
  • 2020-01-24
相关资源
最近更新 更多