#mysql #node.js #sequelize.js
Вопрос:
Поэтому я пытался сохранить точку GeoJSON в своей базе данных MySQL с помощью sequelize, и я продолжаю получать ошибку TypeError: Не удается прочитать свойство «длина» неопределенного. Я следил за документами о формате, в котором он должен быть сохранен, но вся остальная информация не сохранится без проблем, если я не попытаюсь сохранить точку с его помощью. Вот проблемная область:
// Geocode city and state provided by user
const geocodedData = await geocoder.geocode(`${city}, ${state}`)
console.log(geocodedData)
const latitude = geocodedData[0].latitude
const longitude = geocodedData[0].longitude
const point = { type: 'Point', cooridinates: [latitude,longitude] }
console.log(point)
// Create user
try {
user = await User.create(
Object.assign({ firstName, lastName, username, email, password, city, state, geo: point })
)
} catch (err) {
console.log(err)
return next(new ErrorResponse('Error saving data!', 400))
}
Вот моя модель и миграция вместе с ней на случай, если там возникнет ошибка.
const { Model } = require("sequelize")
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken')
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
email: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
password: {
type: DataTypes.STRING,
allowNull: false
},
city: {
type: DataTypes.STRING,
allowNull: false
},
state: {
type: DataTypes.STRING,
allowNull: false
},
geo: {
type: DataTypes.GEOMETRY('POINT'),
allowNull: true
}
}, {
hooks: {
beforeCreate: async (user) => {
if (user.password) {
const salt = await bcrypt.genSaltSync(10, 'a');
user.password = bcrypt.hashSync(user.password, salt);
}
},
beforeUpdate:async (user) => {
if (user.password) {
const salt = await bcrypt.genSaltSync(10, 'a');
user.password = bcrypt.hashSync(user.password, salt);
}
}
},
instanceMethods: {
validPassword: (password) => {
return bcrypt.compareSync(password, this.password);
},
getJwtToken: () => {
return token
}
}
})
User.prototype.validPassword = async (password, hash) => {
return await bcrypt.compareSync(password, hash);
}
User.prototype.getJwtToken = async (user) => {
const id = user.id
const email = user.email
return token = await jwt.sign(
{ id: id, email: email },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRE })
}
User.associate = function () {
}
return User
}
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
await queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
firstName: Sequelize.STRING,
lastName: Sequelize.STRING,
username: Sequelize.STRING,
email: Sequelize.STRING,
password: Sequelize.STRING,
city: Sequelize.STRING,
state: Sequelize.STRING,
geometry: Sequelize.GEOMETRY('POINT')
})
},
down: async (queryInterface, Sequelize) => {
await queryInterface.dropTable('Users')
}
};
I logged out the geocoding first to make sure it works and there are no problems there (as far as i can tell) but when i go to save it, that is when the error is thrown. I have tried formatting it differently to no avail either. I’m new to sequelize so I’m sure I’m overlooking something simple. Any help would be greatly appreciated