문서 메뉴
문서 홈
/ / /
Node.js
/ /

정의되지 않은 값

이 페이지의 내용

  • 개요
  • 정의되지 않은 값 무시
  • 정의되지 않은 값의 직렬화 범위 설정

이 가이드에서는 드라이버가 undefined 값을 직렬화하는 방법을 제어하는 방법을 배울 수 있습니다. 기본적으로 드라이버는 쓰기 작업 중에 undefined 값을 null 값으로 직렬화합니다.

드라이버가 직렬화 중에 undefined 값이 있는 필드를 무시하도록 하려면 ignoreUndefined 설정을 true(으)로 설정하세요. 이 설정을 지정하면 드라이버는 undefined 값을 사용하여 필드를 직렬화하지 않습니다.

다음 예제에서는 두 개의 문서를 삽입합니다. 첫 번째 삽입 작업에는 ignoreUndefined 설정이 true로 설정되어 있으므로 드라이버는 해당 작업에서 salesTax 필드를 직렬화하지 않습니다. 두 번째 작업은 null 값을 포함하는 salesTax 필드가 있는 문서를 삽입합니다.

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 설정을 다시 지정하여 상속된 설정을 재정의할 수 있습니다.

예를 들어 collection 객체에서 ignoreUndefined을(를) true(으)로 설정하면 해당 collection에서 실행하는 개별 쓰기 작업에서 이 설정을 재정의할 수 있습니다.

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 }
);

돌아가기

BSON 설정