文档菜单
文档首页
/ / /
Node.js 驱动程序
/ /

未定义值

本页内容

  • 概述
  • 忽略未定义值
  • 设置序列化未定义值的范围

在这份指南中,您可以学习如何控制驱动程序序列化undefined 值。默认情况下,在写入操作期间,驱动程序将 undefined 值序列化为 null 值。

为了使驱动程序在序列化期间忽略具有 undefined 值的字段,请将 ignoreUndefined 设置为 true。指定此设置时,驱动程序 不会 序列化具有 undefined 值的字段。

以下示例插入两个文档。第一次插入操作将 ignoreUndefined 设置为 true,因此驱动程序不序列化该操作中的 salesTax 字段。第二次操作插入一个具有 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 }
);

返回

BSON 设置