본문 바로가기
개발로그/ReactNative

다이어리 앱을 만들면서 연습해보자. - mongoDB 연동(Realm open/스키마 정의 하기)

by 그리너리디밸로퍼 2023. 2. 14.

이전글 

처음부터 다시 해보는 npx create-react-native-app dear-diary with ios 세팅! 나만의 프리셋

 다이어리 앱을 만들면서 연습해보자. - 모듈설치 /Home / Write Screen

 

 

mongoDB 연동(Realm open/스키마 정의 하기)

Realm (by mongoDB) 설치 

npm install realm

#for mac, ios
npx pod-install ios

mongoDB와 연동할 수 있는 SDK로 realm을 설치합니다.(휴대폰 내부에 DB가 필요할 때 사용)

 

모델 정의하기 (define model)

레퍼런스에 있는 example schema 를 보고 작성합니다. 

const FeellingSchema = {
  name: "feelling",
  properties: {
    _id: "int",
    emotion: "string",
    message: "string",
  },
  primaryKey: "_id",
};

Realm에 접속하기 (open realm)

메모리에 있는 realm에 접속하기 위해 아래와 같이 사용합니다  (= 데이터베이스인 MongoDB와 연결점을 만들어줍니다.) Realm.open은 configuration 으로 path,schema, inMemory.. 등을 주입할 수 있습니다.

# 메모리에 있는 realm의 경우
const realm = await Realm.open({
  inMemory: true,
  schema: [Car], // 스키마가 여러개 있다면 [Car, User... ]
});

# 로컬이 아닌 장소에 있는 경우  
const realm = await Realm.open({
  path:"myrealm", // path 를 작성한다.
  schema: [Car],  
});

# 사용하고 난 뒤에는 꼭 닫아야합니다. 
realm.close();

접속하는 행위는 앱이 기동하기 전에 미리 해둬야하므로 주로 컴포넌트가 "로딩"되기 전에 하게됩니다. 대략적인 과정은 아래와 같습니다. 

 

App Loading은 컴포넌트를 랜더링 하기 전에 사용자에게는 Splash screen 이 보여지는 상태에서 실행됩니다.  그 후 컴포넌트들이 랜더링 됩니다. 

App Loading 설치 

expo install expo-app-loading

#for only mac, ios
npx pod-install ios

expo App Loading 을 이용해서 Realm open 하기

아래 코드가 주요 동작이다. import와 스키마정의는 중복되어 생략했다.

export default function App() {
// ready hook 생성
  const [ready, setReady] = useState(false);
  
  // 로딩시에 realm을 open 한다.
  const startLoading = async () => {
    const realm = await Realm.open({
      path: "dear-diaryDB",
      schema: [FeelingSchema],
    });
    // 잘 연동 되었는지 확인하기 위해 로그를 찍어본다.
    console.log(realm);
  };
  
  // 로딩이 끝나면 ready state를 true 로 변경한다.
  const onFinish = () => setReady(true);
  
  // ready 가 true 상태가 아니면 AppLoading component를 실행한다.
  if (!ready) {
    return (
      <AppLoading
        onError={console.error}
        startAsync={startLoading}
        onFinish={onFinish}
      />
    );
  }
  
  return (
    <NavigationContainer>
      <Navigator />
    </NavigationContainer>
  );
}

다음글 

2023.02.17 - [개발로그/ReactNative] - 다이어리 앱을 만들면서 연습해보자. - Write 화면 구현하기

 

728x90

댓글