简体   繁体   English

“错误”:“无法读取未定义的属性‘findOne’”

[英]“error”: “Cannot read property 'findOne' of undefined”

Hello everybody !!大家好 !! Here I have a big problem, I would like to do a registration in back with Node.js sequelize and mySql.这里我有一个大问题,我想用 Node.js sequelize 和 mySql 做一个注册。 I looked here and there but I did not find the answer to my problem so I came to ask you for help.我四处寻找,但我没有找到问题的答案,所以我来寻求帮助。 With mongoDb, it was easier but I admit that I am going in circles.使用 mongoDb,它更容易,但我承认我在兜圈子。

Here is my code:这是我的代码:

 // Importation : // Bcrypt: const bcrypt = require("bcrypt"); // Jsonwebtoken d'authentification: const jwt = require("jsonwebtoken"); // Import du models user: const models = require("../models/user") ////////////////////////////////////////////////////////////////////////////////////////////// // Fonction/ // Incription: exports.signup = (req, res) => { const username = req.body.username; const email = req.body.email; const password = req.body.password; const bio = req.body.bio; const admin = req.body.admin; console.log(req.body) try { models.User.findOne({ attributes: ['email'], where: { email: email } }) .then((userFound => { if (!userFound) { bcrypt.hash(password, 10, function (err, bcryptPassword) { const newUser = models.User.create({ username : username, email : email, password : bcryptPassword, bio : bio, admin : false }) .then(newUser => { res.status(201).json({ 'userId': newUser.id }) }) .catch(err => { res.status(500).json({ 'error': 'Impossible d\\'ajouter un utilisateur' }) }) }) } else { return res.status(409).json({ error: 'Ce compte existe déjà ' }) } }) .catch((err) => res.status(500).json({ 'err': err + 'Impossible de vérifier l\\'utilisateur', }) ) ) }catch (error) { res.status(400).json({ error: error.message }); } }

邮递员控制台的响应

And the model User:和模型用户:

 'use strict' const { db } = require('../config/connexion') const { Sequelize, DataTypes } = require('sequelize') const user = db.define('User', { // Model attributes are defined here username: DataTypes.STRING, email: DataTypes.STRING, password: DataTypes.STRING, bio: DataTypes.TEXT, admin: DataTypes.BOOLEAN, }) module.exports = user

and connexion.js:和 connexion.js:

 // Connexion de sequelize à mysql: const { Sequelize } = require('sequelize') const db = new Sequelize( process.env.NAMEDB, process.env.USERDB, process.env.PASSWORDDB, { host: process.env.HOSTDB, dialect: process.env.DIALECTDB, pool: { min: 0, // nombre minimum de connexion dans le pool max: 5, // nombre maximum de connexion dans le pool acquire: 30000, // durée maximale, en millisecondes, pendant laquelle ce pool essaiera d'obtenir la connexion avant de lancer une erreur idle: 10000, // temps maximum, en millisecondes, pendant lequel une connexion peut être inactive avant d'être libérée }, } ) ////////////////////////////////////////////////////////////////////////////////////////////// // Etablit la connexion à mysql: const dbConnect = async (db) => { await db .authenticate() .then(() => { db.sync() console.log('Connecté à la base de données MySQL!') }) .catch((err) => { console.error('error: ' + err.message) setTimeout(() => { dbConnection(db) }, 5000) }) } ////////////////////////////////////////////////////////////////////////////////////////////// // Exportation: module.exports = { db, dbConnect, }

Certainly there is still a lot to do, but being a beginner I improve as I go.当然还有很多事情要做,但是作为初学者,我会不断改进。

Do not be angry with me if my English is not at the top, I admit that it is not my strong point.如果我的英语没有达到顶峰,请不要生我的气,我承认这不是我的强项。

Thanking you in advance for all the help provided.预先感谢您提供的所有帮助。

You are directly setting the export object equal to the user object.您直接将导出对象设置为等于用户对象。

When you do this const models = require("../models/user") , models is equal to the user value directly.当你这样做时const models = require("../models/user")models直接等于user值。

You can directly use models.findOne .您可以直接使用models.findOne Read this这个

Check your "model" file to see if the "User" model exists there.检查您的“模型”文件以查看其中是否存在“用户”模型。 Also check if you are using the 'module.exports'还要检查您是否正在使用“module.exports”

You are exporting the User model directly, but calling it like it is in an object property named User .您正在直接导出User模型,但像在名为User的对象属性中一样调用它。 You can either access it directly, changing:您可以直接访问它,更改:

models.User.findOne

to:到:

models.findOne

and then you'd probably want to rename models to User .然后您可能希望将models重命名为User

Or change your export to:或者将您的导出更改为:

module.exports = { User: user };

You are setting the user variable to be the export of the file您正在将user变量设置为文件的导出

module.exports = user

You then import the user variable as models .然后将user变量作为models导入。

const models = require("../models/user")

this means that you do not need to access user as a property.这意味着您不需要将user作为属性访问。 Instead use:而是使用:

models.findOne({ // Changed from models.User to models
    attributes: ["email"],
    where: {
        email: email,
    },
});

This should stop your current error, but you will keep on getting errors until you change all instances of models.User to models .这应该会停止您当前的错误,但您将继续收到错误,直到您将models.User所有实例models.Usermodels

Your main file should end up looking like this:您的主文件最终应如下所示:

 // Importation : // Bcrypt: const bcrypt = require("bcrypt"); // Jsonwebtoken d'authentification: const jwt = require("jsonwebtoken"); // Import du models user: const models = require("../models/user"); ////////////////////////////////////////////////////////////////////////////////////////////// // Fonction/ // Incription: exports.signup = (req, res) => { const username = req.body.username; const email = req.body.email; const password = req.body.password; const bio = req.body.bio; const admin = req.body.admin; console.log(req.body); try { models .findOne({ attributes: ["email"], where: { email: email, }, }) .then( ((userFound) => { if (!userFound) { bcrypt.hash(password, 10, function (err, bcryptPassword) { const newUser = models .create({ username: username, email: email, password: bcryptPassword, bio: bio, admin: false, }) .then((newUser) => { res.status(201).json({ userId: newUser.id, }); }) .catch((err) => { res.status(500).json({ error: "Impossible d'ajouter un utilisateur", }); }); }); } else { return res.status(409).json({ error: "Ce compte existe déjà ", }); } }).catch((err) => res.status(500).json({ err: err + "Impossible de vérifier l'utilisateur", }) ) ); } catch (error) { res.status(400).json({ error: error.message, }); } };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM