我正在尝试设置一个快速服务器,该服务器之前已经可以运行。但是当我在文件上编写一些功能时,由于指定的属性,它开始崩溃。
文件(index.js):
fs = require('fs')
const path = require('path')
const Sequelize = require ('sequelize')
const config = require('../config/config')
const db = {}
/* const sequelize = require('../databaseConfig');
const { DataTypes } = require('sequelize'); */
/* INICIANDO A INSTÂNCIA DB DO SEQUELIZE */
const sequelize = new Sequelize(
config.db.database,
config.db.user,
config.db.password,
config.db.options
)
/************* */
fs
.readdirSync(__dirname) //ler um diretório e passar um array com diferentes arquivos.
.filter((file) =>
file !== 'index.js'
) //filtrar cada arquivo que seja equivalente ao "index.js" (não queremos o arquivo "index.js", mas queremos todos os outros arquivos de "models").
/* PARA CADA ARQUIVO QUE FOR ENCONTRADO... */
.forEach((file) => {
// VVVV será declarado um modelo que armazenará seu caminho relativo para ser usado com o sequelize.
const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes)
//VVVV setar o nome do db como descrito abaixo.
db[model.name] = model
})
/******* */
db.sequelize = sequelize //acesso ao objeto sequelize.
db.Sequelize = SequeLize //acesso ao objeto CamelCase do SequeLize.
module.exports = db
错误代码(node.js):
C:\Users\pedro\OneDrive\Documentos\GitHub\autiapp-tcc-pedro\servidor\models\index.js:29
db[model.name] = model
^
TypeError: Cannot read properties of undefined (reading 'name')
at C:\Users\pedro\OneDrive\Documentos\GitHub\autiapp-tcc-pedro\servidor\models\index.js:29:18
at Array.forEach (<anonymous>)
at Object.<anonymous> (C:\Users\pedro\OneDrive\Documentos\GitHub\autiapp-tcc-pedro\servidor\models\index.js:25:6)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\pedro\OneDrive\Documentos\GitHub\autiapp-tcc-pedro\servidor\app.js:5:21)
[nodemon] app crashed - waiting for file changes before starting...
有人可以帮助我吗?谢谢!
我尝试在函数之前导入变量,但它也不起作用。
此处的解决方案取决于您目录中的文件。我不知道这些文件是什么,所以我能给你的最好答案是帮助你调试代码。
TypeError: Cannot read properties of undefined (reading ...)
是javascript中的一个常见错误。这意味着您正在尝试访问对象的属性,但该对象是undefined
。在你的情况下,model
是undefined
。如果您在带有 console.log('This is my model ---', model)
的行之前添加 db[model.name] = model
语句,您就会明白我的意思。文件数组中的第一个文件可能会发生这种情况。最后一个文件可能会发生这种情况。要了解哪些文件导致此问题,您还应该 console.log
file
变量。这将帮助您查明确切的问题。