Overview
このガイドでは、ドライバーが undefined値を直列化する方法を制御する方法を学習できます。 デフォルトでは、ドライバーは書込み操作中にundefined値をnull値として直列化します。
未定義の値を無視する
直列化中にドライバーがundefined値を持つフィールドを無視するようにするには、 ignoreUndefinedの設定をtrueに設定します。 この設定を指定すると、ドライバーはundefined値を持つフィールドを直列化しません。
次の例では、2 つのドキュメントを挿入しています。 最初の挿入操作では、 ignoreUndefined設定がtrueに設定されているため、ドライバーはその操作でsalesTaxフィールドを直列化しません。 2 番目の 操作では、 salesTaxフィールドにnull値を持つドキュメントが挿入されます。
await myColl.insertOne( { state: "Montana", salesTax: undefined, }, { ignoreUndefined: true } ); await myColl.insertOne({ state: "New Hampshire", salesTax: undefined, });
ドキュメントは、 コレクションに次のように表示されます。
{ _id: ..., state: "Montana", }, { _id: ..., state: "New Hampshire", salesTax: null }
未定義の値を直列化するためのスコープの設定
ignoreUndefined設定は次のレベルで指定できます。
クライアント レベル
データベース レベル
コレクション レベル
操作レベル
ignoreUndefined設定は、それを指定したオブジェクト インスタンスの範囲と、そのインスタンスから作成された他のオブジェクトに自動的に適用されます。
たとえば、データベース オブジェクトをインスタンス化するときにignoreUndefined設定を設定すると、そのオブジェクトから作成されたすべてのコレクション インスタンスが 設定を継承します。 さらに、そのコレクション インスタンスで呼び出す操作も、 設定を継承します。
次の例では、 myDBデータベース オブジェクトからignoreUndefined設定を継承する検索とアップデートの操作を実行します。 この操作ではドライバーがgasTaxフィールドを無視するため、データは変更されません。
const myDB = client.db("test", { ignoreUndefined: true }); // The collection inherits the ignoreUndefined setting const myColl = myDB.collection("states"); // Any write operation will not serialize undefined values await myColl.findOneAndUpdate( { state: "Georgia" }, { $set: { gasTax: undefined } } );
継承された設定を上書きするには、任意のレベルで再度ignoreUndefined設定を再度指定できます。
たとえば、コレクション オブジェクトでignoreUndefinedをtrueに設定すると、そのコレクションに対して実行する個々の書込み操作で 設定を上書きできます。
const myColl = myDB.collection("states", { ignoreUndefined: true }); // The insert operation will not serialize undefined values await myColl.insertOne({ state: "South Dakota", capitalGainsTax: undefined, }); // The insert operation will serialize undefined values await myColl.insertOne( { state: "Texas", capitalGainsTax: undefined }, { ignoreUndefined: false } );