Sequelize - findOrCreate 사용하기

Hyunwoo Seo·2022년 9월 11일
0

Sequelize

목록 보기
2/3
post-thumbnail

findOrCreate

The method findOrCreate will create an entry in the table unless it can find one fulfilling the query options. In both cases, it will return an instance (either the found instance or the created instance) and a boolean indicating whether that instance was created or already existed.

The where option is considered for finding the entry, and the defaults option is used to define what must be created in case nothing was found. If the defaults do not contain values for every column, Sequelize will take the values given to where (if present).

Let's assume we have an empty database with a User model which has a username and a job.

const [user, created] = await User.findOrCreate({
  where: { username: 'sdepold' },
  defaults: {
    job: 'Technical Lead JavaScript'
  }
});
console.log(user.username); // 'sdepold'
console.log(user.job); // This may or may not be 'Technical Lead JavaScript'
console.log(created); // The boolean indicating whether this instance was just created
if (created) {
  console.log(user.job); // This will certainly be 'Technical Lead JavaScript'
}

공식문서에서는 findOrCreate 는 특정 요소를 검색하거나, 존재하지 않으면 새로 생성하는 것으로 나와있다.

DB에 특정 요소가 존재하는지 검사한 후, 존재한다면 해당 인스턴스를 반환하고 그렇지 않다면 새로 생성한다.

User.findOrCreate({ where: { username: 'sdepold' }, defaults: { job: 'Technical Lead JavaScript' } }).spread((user, created) => {
  console.log(
    user.get({
      plain: true,
    })
  );
  console.log(created);

  /*
     findOrCreate 메서드는 검색되었거나 또는 생성된 객체를 포함한 배열, 그리고 boolean값을 반환합니다. 여기서 boolean값은, 새 객체가 생성되었을 경우 true, 그렇지 않을 경우 false입니다.

    [ {
        username: 'sdepold',
        job: 'Technical Lead JavaScript',
        id: 1,
        createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
        updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
      },
      true ]

 위의 예시에서 "spread" 메서드는 배열을 user와 created 2개 부분으로 나누어 이어지는 콜백에 인자로 전달합니다. 따라서 "user"는 반환된 배열의 0번째 인덱스에 존재하는 객체이고, "created"는 true값을 갖는 boolean 변수입니다.
    */
});

해당문서를 확인하고 작업해봤지만 spread 에서 에러가 났다.

Sequelize findOrCreate(...).spread is not a function

이런식이었는데 구글링으로도 찾을 수가 없었다.

값이 두개가 나와서 then() 대신 spread() 를 써야 한다고 나와있는데 vscode 내부 메서드에서도 spread() 는 목록에 없고 then() 만 있었다.

그래서 then() 을 사용했고 사용이 됐다..

0개의 댓글