对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

未定义的值

在本指南中,您可以学习控制驱动程序对 undefined 值进行序列化的方式。默认情况下,驱动程序在写入操作期间将 undefined 值序列化为 null 值。

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

以下示例插入了两个文档。第一个插入操作将 ignoreUndefined 设置设置为 true,因此驱动程序不会在该操作中序列化 salesTax 字段。第二个操作插入包含值为 nullsalesTax 字段的文档:

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