컨트롤러에서 Sequelize 모델 사용자 정의 함수를 호출할 수 없습니다.

프랭클린 에코

이 사용자 정의 기능은 다음과 같은 후속 모델을 가지고 있습니다.

'use strict';
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const config = require('../../config');

module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
  type: DataTypes.STRING,
  primaryKey: true
},
name: DataTypes.STRING,
email: DataTypes.STRING,
bio: DataTypes.STRING,
phone: DataTypes.STRING,
username: DataTypes.STRING,
password: {
  type: DataTypes.STRING,
  set(value){
    this.setDataValue('password', bcrypt.hashSync(value, 10));
  }
}
}, {});

User.generateJWT = function(id, username) {
return jwt.sign({
  id: id,
  username: username,
  expiresIn: config.auth.exp
}, config.secret);
};

User.toAuthJson = async function() {
return {
  name: this.name,
  email: this.email,
  bio: this.bio,
  phone: this.phone,
  username: this.username
};
};

User.validatePassword = function(password, passwordHash){
return bcrypt.compareSync(password, passwordHash);
};

User.isUniqueEmail = async function(email) {
  return await User.findOne({where: {email}}) === null;
};

User.isUniqueUsername = async function(username) {
  return await User.findOne({where: {username}}) === null;
};

User.isUniquePhone = async function(phone) {
 return await User.findOne({where: {phone}}) === null;
};
User.associate = function(models) {
// associations can be defined here
};
return User;
};

다음과 같은 컨트롤러:

const {User} = require('../database/models/');

module.exports.register = async (req, res, next) => {
    try {
       const isUniqueEmail = await User.isUniqueEmail(req.body.email);
        if (!isUniqueEmail) return  res.status(422).json({'message': 'email already exists'});

        const isUniquePhone = await User.isUniquePhone(req.body.phone);
        if (!isUniquePhone) return  res.status(422).json({'message': 'phone already exists'});

        const isUniqueUsername = await User.isUniqueUsername(req.body.username);
        if (!isUniqueUsername) return  res.status(422).json({'message': 'username already exists'});

         const user = await User.create(req.body);
         console.log(user.toAuthJson()); //an error occurs here
        return res.status(201).json({user: user.toAuthJson()});
    }catch (e) {
        next(e);
    }
 };

이 user.toAuthJson과 같은이 컨트롤러에서 toAuthJson 기능에 액세스하려고 할 때. "작은 u를 주목하십시오." TypeError: User.toAuthJson은 함수가 아닙니다. 정상적으로 접근할 수 있어야 합니다. 돕다. 감사 해요

CBR

User.toAuthJson현재 클래스 메서드입니다. 다른 함수와 마찬가지로 다음과 같이 호출해야 합니다 User.toAuthJson(user).

아마도 인스턴스 메소드를 찾고 있을 것이므로 대신 프로토타입에서 정의하고 싶을 것입니다.

User.prototype.toAuthJson = function() {
  return {
    name: this.name,
    email: this.email,
    bio: this.bio,
    phone: this.phone,
    username: this.username
  };
};

이제 다음 User과 같이 인스턴스에서 호출할 수 있습니다 .

console.log(user.toAuthJson());

async이 함수는 비동기식으로 아무것도 하지 않기 때문에 생략했습니다 .

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

CodeIgniter는 컨트롤러의 모델에서 함수를 호출 할 수 없습니다.

AngularJs ControllerAs 접근 방식을 사용하여 자식 컨트롤러에서 부모 컨트롤러의 함수를 어떻게 호출 할 수 있습니까?

한 컨트롤러 메서드에서 설정된 모델 속성의 속성을 다른 컨트롤러 메서드에서 사용할 수 없습니다.

ViewSettingsCustomItem 내에서 사용자 지정 컨트롤에 모델을 사용할 수 없습니다.

함수를 호출한 컨트롤러의 모델 함수에서 변수 데이터 사용

확장 된 Magento 모델 내에서 사용자 지정 메서드를 호출 할 수 없습니다.

사용자 정의 함수에서 라이브러리 함수를 호출할 수 없습니다.

codeigniter의 다른 컨트롤러에서 정적 함수를 호출 할 수 없습니다. 왜?

부모 컨트롤러에서 자식 컨트롤러의 함수 호출

Laravel 5.2의 컨트롤러에서 모델 함수 호출

HTML보기 또는 컨트롤러의 모델에서 역할 함수 호출

모델의 컨트롤러 변수에 액세스 할 수 없습니다.

컨트롤러의 생성자에서 Auth :: user ()를 호출 할 수 없습니다.

Polymer에서 사용자 정의 함수 호출을 할 수 없습니다.

Aurelia에서 사용자 지정 요소가 호출 할 포함 뷰 모델의 함수를 바인딩 할 수 있습니까?

Typescript Sequelize Typescript Sequelize TypeError : 클래스 생성자 모델은 'new'없이 호출 할 수 없습니다.

Angularjs의 Factory를 사용하여 한 컨트롤러에서 다른 컨트롤러로 함수 호출

codeigniter-컨트롤러에서 모델 결과를 사용하여 모델에서 다른 함수를 호출합니다.

각도 재질 모달 대화 상자에서 컨트롤러의 속성을 설정할 수 없습니다.

AngularJS의 자식 컨트롤러에서 함수를 어떻게 호출 할 수 있습니까?

컨트롤러에서 Rails 5 사용자 정의 모듈 기능을 찾을 수 없습니다.

격리 된 범위를 사용할 때 지시문에서 컨트롤러의 함수를 호출합니까?

사용자 지정 셀에서 UISwitch를 사용하여 새 컨트롤러로 이동할 수 없습니다.

magento 1.9의 컨트롤러에서 도우미 함수를 호출 할 수 없습니다.

AngularJS : http 호출의 모델 데이터를 지시문에서 사용할 수 없습니다.

연결된 모델의 Rails 사용자 ID, 왜 사용자 정보를 호출 할 수 없습니까?

콘솔 또는 컨트롤러에서 Rails 모델 속성을 설정할 수 없습니다.

자식 UI에서 부모 컨트롤러의 메서드에 액세스 할 수 없습니다.

Opencart 2에서 사용자 지정 컨트롤러를로드 할 수 없습니다.

TOP 리스트

  1. 1

    Ionic 2 로더가 적시에 표시되지 않음

  2. 2

    JSoup javax.net.ssl.SSLHandshakeException : <url>과 일치하는 주체 대체 DNS 이름이 없습니다.

  3. 3

    std :: regex의 일관성없는 동작

  4. 4

    Xcode10 유효성 검사 : 이미지에 투명성이 없지만 여전히 수락되지 않습니까?

  5. 5

    java.lang.UnsatisfiedLinkError : 지정된 모듈을 찾을 수 없습니다

  6. 6

    rclone으로 원격 디렉토리의 모든 파일을 삭제하는 방법은 무엇입니까?

  7. 7

    상황에 맞는 메뉴 색상

  8. 8

    SMTPException : 전송 연결에서 데이터를 읽을 수 없음 : net_io_connectionclosed

  9. 9

    정점 셰이더에서 카메라에서 개체까지의 XY 거리

  10. 10

    Windows cmd를 통해 Anaconda 환경에서 Python 스크립트 실행

  11. 11

    다음 컨트롤이 추가되었지만 사용할 수 없습니다.

  12. 12

    C #에서 'System.DBNull'형식의 개체를 'System.String'형식으로 캐스팅 할 수 없습니다.

  13. 13

    JNDI를 사용하여 Spring Boot에서 다중 데이터 소스 구성

  14. 14

    Cassandra에서 버전이 지정된 계층의 효율적인 모델링

  15. 15

    복사 / 붙여 넣기 비활성화

  16. 16

    Android Kotlin은 다른 활동에서 함수를 호출합니다.

  17. 17

    Google Play Console에서 '예기치 않은 오류가 발생했습니다. 나중에 다시 시도해주세요. (7100000)'오류를 수정하는 방법은 무엇입니까?

  18. 18

    SQL Server-현명한 데이터 문제 받기

  19. 19

    Seaborn에서 축 제목 숨기기

  20. 20

    ArrayBufferLike의 typescript 정의의 깊은 의미

  21. 21

    Kubernetes Horizontal Pod Autoscaler (HPA) 테스트

뜨겁다태그

보관