LoginSignup
1

More than 3 years have passed since last update.

mongoose でデータの登録直後に検索を行う際の注意点

Posted at

mongooseではデータの検索(find)や登録(save)は非同期で処理されるため、処理の順番に注意する必要があります。

検索(find)について

検索(find系の関数)については、awaitを利用して検索処理の結果を待つことができます。

コード
  console.log('before find.');
  let result = await hogeCollection.find((err, result) => { console.log('found.'); });
  console.log('after find.');
結果
before find.
found.
after find.

登録(save)について

登録(saveやcreate)については、awaitでは処理結果を待つことができません。

コード
  console.log('before save.');
  await foo.save((err, result) => { console.log('saved.'); });
  console.log('after save.');
結果
before save.
after save.  ← 登録処理のコールバックより先に実行されている
saved.

つまり?

例えば、データを一旦DBに登録してから、登録したデータを含めて検索をしたい場合、上記のコードを登録→更新の順に並べても、登録が完了するより先に検索が走ってしまう場合があり、期待した結果が得られないことがあります。

どうすればよい?

登録が完了してから検索が実行されるように、then()を利用しましょう。

コード
  foo.save().then(() => {
    hogeCollection.find({}).then((result) => {
      // 検索してから実行したい処理
    });
  });

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1