TypeError: 無法讀取未定義的屬性(閱讀 'create'),並在 sequelize expressjs nodejs 中發表。



这是我的代码片段

文件夹诈骗

backendstuff (the express app)
- models/currentweather.js
- models/sequelize.js
- routes/weather.js
app.js

models/currentweather.js

const { Sequelize, DataTypes, Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {

const CurrentWeather = sequelize.define("CurrentWeather", {
// Model attributes are defined here
name: DataTypes.STRING,
region: DataTypes.STRING,
country: DataTypes.STRING,
lat: DataTypes.FLOAT,
lon: DataTypes.FLOAT,
tz_id : DataTypes.STRING    
});
return CurrentWeather;
}

models/sequalize.js

const Sequelize = require("sequelize");
const CWeatherModel = require('./currentweather');
const FWeatherModel = require('./forecastweather');
const sequelize = new Sequelize(
'climate_db',
'uname',
'password',
{
host: 'localhost',
dialect: 'mysql'
}
);
const CWeather = CWeatherModel(sequelize, Sequelize)
const FWeather = FWeatherModel(sequelize, Sequelize)
sequelize.authenticate().then(() => {
console.log('Connection has been established successfully.');
}).catch((error) => {
console.error('Unable to connect to the database: ', error);
});
// sequelize.sync()
//   .then(() => {
//     console.log(`Database & tables created!`)
//   })

module.exports = {
CWeather,
FWeather
}

路线/天气.js

var express = require('express');
var router = express.Router();
const axios = require('axios');
const { CurrentWeather } = require('../models/currentweather');
const { ForecastWeather } = require('../models/forecastweather');
// Added as per recommendation
const { Sequelize, DataTypes, Model } = require('sequelize');

require('dotenv').config();
var request=require('request');
var apiconf = require('../apiconfig.json');
var apikey = process.env.APIKEY,
apiBaseurl = 'http://api.weatherapi.com/v1/';
router.get('/current', function(req, res, next){
// API Returns the json - working!!
apiurl = 'https://someapiurl.com?weather';

axios.get(apiurl)
.then(response => {
console.log(response.data);
// Storing the Response in location piece from the huge response
// Throws this error now:
// TypeError: CurrentWeather is not a function 
const cweather =  CurrentWeather(Sequelize, DataTypes).create({ 
name: location.name,
region: location.region,
country: location.country,
lat: location.lat,
lon: location.lon,
tz_id: location.tz_id
});
cweather.save();
return res.json(response.data);
})
})

看起来一切都很好,但我收到了这个错误,我缺少什么?

const cweather =  CurrentWeather.create({ 
^
TypeError: Cannot read properties of undefined (reading 'create')

currentweather.js导出一个函数,该函数返回Sequelize的CurrentWeather的实例,而您正试图将该函数本身视为Sequelize创建的函数。

您忘记将sequelizeDataTypes传递给函数。您的weather.js代码应该是这样的:

const cweather =  CurrentWeather(sequelizeInstance, yourDataTypes).create({ 
name: location.name,
region: location.region,
country: location.country,
lat: location.lat,
lon: location.lon,
tz_id: location.tz_id
});

最新更新