文档
Document.prototype.$assertPopulated()Document.prototype.$clearModifiedPaths()Document.prototype.$clone()Document.prototype.$createModifiedPathsSnapshot()Document.prototype.$errorsDocument.prototype.$getAllSubdocs()Document.prototype.$getPopulatedDocs()Document.prototype.$ignore()Document.prototype.$inc()Document.prototype.$init()Document.prototype.$isDefault()Document.prototype.$isDeleted()Document.prototype.$isEmpty()Document.prototype.$isModified()Document.prototype.$isNewDocument.prototype.$localsDocument.prototype.$markValid()Document.prototype.$opDocument.prototype.$parent()Document.prototype.$populated()Document.prototype.$restoreModifiedPathsSnapshot()Document.prototype.$session()Document.prototype.$set()Document.prototype.$timestamps()Document.prototype.$validate()Document.prototype.$whereDocument.prototype.depopulate()Document.prototype.directModifiedPaths()Document.prototype.equals()Document.prototype.errorsDocument.prototype.get()Document.prototype.getChanges()Document.prototype.idDocument.prototype.init()Document.prototype.inspect()Document.prototype.invalidate()Document.prototype.isDirectModified()Document.prototype.isDirectSelected()Document.prototype.isInit()Document.prototype.isModified()Document.prototype.isNewDocument.prototype.isSelected()Document.prototype.markModified()Document.prototype.modifiedPaths()Document.prototype.overwrite()Document.prototype.parent()Document.prototype.populate()Document.prototype.populated()Document.prototype.replaceOne()Document.prototype.save()Document.prototype.schemaDocument.prototype.set()Document.prototype.toJSON()Document.prototype.toObject()Document.prototype.toString()Document.prototype.unmarkModified()Document.prototype.updateOne()Document.prototype.validate()Document.prototype.validateSync()
Document.prototype.$assertPopulated()
参数
path«String|Array[String]» 要检查的路径或路径数组。如果给定的任何路径没有填充,$assertPopulated会抛出错误。[values]«Object» 可选的要$set()的值。如果您想手动填充路径并断言路径已在一个调用中填充,则此方法很方便。
返回值
- «Document» this
如果给定的路径未填充,则抛出错误
示例
const doc = await Model.findOne().populate('author');
doc.$assertPopulated('author'); // does not throw
doc.$assertPopulated('other path'); // throws an error
// Manually populate and assert in one call. The following does
// `doc.$set({ likes })` before asserting.
doc.$assertPopulated('likes', { likes }); Document.prototype.$clearModifiedPaths()
返回值
- «Document» this
清除文档的已修改路径。
示例
const doc = await TestModel.findOne();
doc.name = 'test';
doc.$isModified('name'); // true
doc.$clearModifiedPaths();
doc.name; // 'test', `$clearModifiedPaths()` does **not** modify the document's data, only change tracking Document.prototype.$clone()
返回值
- «Document» 此文档的副本
返回此文档的副本,其中包含 _doc 和 $__ 的深层克隆。
Document.prototype.$createModifiedPathsSnapshot()
返回值
- «ModifiedPathsSnapshot» 此文档的内部更改跟踪状态的副本
创建此文档的内部更改跟踪状态的快照。您可以稍后使用 $restoreModifiedPathsSnapshot() 重置此文档的更改跟踪状态。
示例
const doc = await TestModel.findOne();
const snapshot = doc.$createModifiedPathsSnapshot(); Document.prototype.$errors
类型
- «property»
包含当前验证 $errors 的哈希。
Document.prototype.$getAllSubdocs()
返回值
- «Array»
获取所有子文档(通过广度优先搜索)
Document.prototype.$getPopulatedDocs()
返回值
- «Array[Document]» 填充的文档数组。如果与该文档关联的没有填充的文档,则为空数组。
获取与该文档关联的所有填充的文档。
Document.prototype.$ignore()
参数
path«String» 要忽略的路径
不要对该路径运行验证,也不要将更改持久化到该路径。
示例
doc.foo = null;
doc.$ignore('foo');
doc.save(); // changes to foo will not be persisted and validators won't be run Document.prototype.$inc()
参数
path«String|Array» 要更新的路径或路径val«Number» 将path递增此值
返回值
- «Document» this
将 path 处的值递增给定的 val。当您对该文档调用 save() 时,Mongoose 将发送一个 $inc 而不是 $set。
示例
const schema = new Schema({ counter: Number });
const Test = db.model('Test', schema);
const doc = await Test.create({ counter: 0 });
doc.$inc('counter', 2);
await doc.save(); // Sends a `{ $inc: { counter: 2 } }` to MongoDB
doc.counter; // 2
doc.counter += 2;
await doc.save(); // Sends a `{ $set: { counter: 2 } }` to MongoDB Document.prototype.$init()
.init 的别名
Document.prototype.$isDefault()
参数
[path]«String»
返回值
- «Boolean»
检查路径是否设置为默认值。
示例
MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
const m = new MyModel();
m.$isDefault('name'); // true Document.prototype.$isDeleted()
参数
[val]«Boolean» 可选,覆盖 mongoose 是否认为文档已删除
返回值
- «Boolean,Document» mongoose 是否认为此文档已删除。
Getter/Setter,确定文档是否已删除。
示例
const product = await product.remove();
product.$isDeleted(); // true
product.remove(); // no-op, doesn't send anything to the db
product.$isDeleted(false);
product.$isDeleted(); // false
product.remove(); // will execute a remove against the db Document.prototype.$isEmpty()
参数
[path]«String»
返回值
- «Boolean»
如果给定的路径为 nullish 或仅包含空对象,则返回 true。对于确定此子文档是否会被 最小化选项 剥离,此方法很有用。
示例
const schema = new Schema({ nested: { foo: String } });
const Model = mongoose.model('Test', schema);
const doc = new Model({});
doc.$isEmpty('nested'); // true
doc.nested.$isEmpty(); // true
doc.nested.foo = 'bar';
doc.$isEmpty('nested'); // false
doc.nested.$isEmpty(); // false Document.prototype.$isModified()
.isModified 的别名
Document.prototype.$isNew
类型
- «property»
布尔标志,指定文档是否为新文档。如果您使用 new 创建文档,则此文档将被视为“新文档”。$isNew 是 Mongoose 用于确定 save() 应该使用 insertOne() 创建新文档还是 updateOne() 更新现有文档的方式。
示例
const user = new User({ name: 'John Smith' });
user.$isNew; // true
await user.save(); // Sends an `insertOne` to MongoDB另一方面,如果您使用 findOne() 或其他 查询操作 从数据库加载现有文档,则 $isNew 将为 false。
示例
const user = await User.findOne({ name: 'John Smith' });
user.$isNew; // falseMongoose 在 save() 成功后立即将 $isNew 设置为 false。这意味着 Mongoose 在 post('save') 钩子运行之前将 $isNew 设置为 false。在 post('save') 钩子中,如果 save() 成功,则 $isNew 将为 false。
示例
userSchema.post('save', function() {
this.$isNew; // false
});
await User.create({ name: 'John Smith' });对于子文档,如果父文档的 $isNew 设置为 true,或者您创建新的子文档,则 $isNew 为 true。
示例
// Assume `Group` has a document array `users`
const group = await Group.findOne();
group.users[0].$isNew; // false
group.users.push({ name: 'John Smith' });
group.users[1].$isNew; // true Document.prototype.$locals
类型
- «property»
空对象,您可以使用它在文档上存储属性。这对于在不与 Mongoose 内部冲突的情况下将数据传递给中间件很有用。
示例
schema.pre('save', function() {
// Mongoose will set `isNew` to `false` if `save()` succeeds
this.$locals.wasNew = this.isNew;
});
schema.post('save', function() {
// Prints true if `isNew` was set before `save()`
console.log(this.$locals.wasNew);
}); Document.prototype.$markValid()
参数
path«String» 要标记为有效的字段
将路径标记为有效,删除现有的验证错误。
Document.prototype.$op
类型
- «property»
包含 Mongoose 当前对该文档执行的操作的字符串。可能是 null、'save'、'validate' 或 'remove'。
示例
const doc = new Model({ name: 'test' });
doc.$op; // null
const promise = doc.save();
doc.$op; // 'save'
await promise;
doc.$op; // null Document.prototype.$parent()
返回值
- «Document»
parent() 的别名。如果此文档是子文档或填充的文档,则返回文档的父文档。否则返回 undefined。
Document.prototype.$populated()
.populated 的别名。
Document.prototype.$restoreModifiedPathsSnapshot()
参数
snapshot«ModifiedPathsSnapshot» 要还原的文档的内部更改跟踪状态快照
返回值
- «Document» this
将此文档的更改跟踪状态还原为给定的快照。请注意,$restoreModifiedPathsSnapshot() 不会修改文档的属性,只会重置更改跟踪状态。
此方法在编写需要在中止事务时还原更改跟踪的 自定义事务包装器 时尤其有用。
示例
const doc = await TestModel.findOne();
const snapshot = doc.$createModifiedPathsSnapshot();
doc.name = 'test';
doc.$restoreModifiedPathsSnapshot(snapshot);
doc.$isModified('name'); // false because `name` was not modified when snapshot was taken
doc.name; // 'test', `$restoreModifiedPathsSnapshot()` does **not** modify the document's data, only change tracking Document.prototype.$session()
参数
[session]«ClientSession» 覆盖当前会话
返回值
- «ClientSession»
与该文档关联的会话的 Getter/Setter。如果您从具有关联会话的查询中 save() 文档,则用于自动设置 session。
示例
const session = MyModel.startSession();
const doc = await MyModel.findOne().session(session);
doc.$session() === session; // true
doc.$session(null);
doc.$session() === null; // true如果这是顶级文档,则设置会话会传播到所有子文档。
Document.prototype.$set()
参数
path«String|Object» 要设置的路径或键/值对对象val«Any» 要设置的值[type]«Schema|String|Number|Buffer|[object Object]» 可选地为“动态”属性指定类型[options]«Object» 可选地指定修改设置行为的选项[options.merge=false]«Boolean» 如果为 true,则设置 嵌套路径 将合并现有值,而不是覆盖整个对象。因此doc.set('nested', { a: 1, b: 2 })变为doc.set('nested.a', 1); doc.set('nested.b', 2);
返回值
- «Document» this
set() 的别名,在内部使用以避免冲突
Document.prototype.$timestamps()
参数
[value]«Boolean» 覆盖当前会话
返回值
- «Document,boolean,undefined,void» 当用作 Getter(无参数)时,将返回一个布尔值,表示时间戳选项状态,如果未设置,则使用“undefined”,否则将返回“this”
Getter/Setter,用于确定此文档是否将在使用 save() 和 bulkSave() 时默认应用时间戳。
示例
const TestModel = mongoose.model('Test', new Schema({ name: String }, { timestamps: true }));
const doc = new TestModel({ name: 'John Smith' });
doc.$timestamps(); // true
doc.$timestamps(false);
await doc.save(); // Does **not** apply timestamps Document.prototype.$validate()
.validate 的别名
Document.prototype.$where
类型
- «property»
将此属性设置为在 Mongoose 保存此文档且 isNew 为 false 时添加额外的查询过滤器。
示例
// Make sure `save()` never updates a soft deleted document.
schema.pre('save', function() {
this.$where = { isDeleted: false };
}); Document.prototype.depopulate()
参数
[path]«String|Array[String]» 要取消填充的特定路径。如果未设置,则将取消填充文档上的所有路径。或多个以空格分隔的路径。
返回值
- «Document» this
参见
获取填充的字段并将其恢复为未填充状态。
示例
Model.findOne().populate('author').exec(function (err, doc) {
console.log(doc.author.name); // Dr.Seuss
console.log(doc.depopulate('author'));
console.log(doc.author); // '5144cf8050f071d979c118a7'
})如果未提供路径,则所有填充的字段都将恢复为未填充状态。
Document.prototype.directModifiedPaths()
返回值
- «Array[String]»
返回已直接修改的路径列表。直接修改的路径是您显式设置的路径,无论是通过 doc.foo = 'bar'、Object.assign(doc, { foo: 'bar' }) 还是 doc.set('foo', 'bar')。
路径 a 可能会出现在 modifiedPaths() 中,但不会出现在 directModifiedPaths() 中,因为 a 的子路径已被直接修改。
示例
const schema = new Schema({ foo: String, nested: { bar: String } });
const Model = mongoose.model('Test', schema);
await Model.create({ foo: 'original', nested: { bar: 'original' } });
const doc = await Model.findOne();
doc.nested.bar = 'modified';
doc.directModifiedPaths(); // ['nested.bar']
doc.modifiedPaths(); // ['nested', 'nested.bar'] Document.prototype.equals()
参数
[doc]«Document» 要比较的文档。如果为假值,则将始终返回“false”。
返回值
- «Boolean»
如果此文档等于另一个文档,则返回 true。
当文档具有匹配的 _id 时,文档被认为是相等的,除非两个文档都没有 _id,在这种情况下,此函数将退回到使用 deepEqual()。
Document.prototype.errors
类型
- «property»
包含当前验证错误的哈希。
Document.prototype.get()
参数
path«String»[type]«Schema|String|Number|Buffer|[object Object]» 可选地为动态属性指定类型[options]«Object»[options.virtuals=false]«Boolean» 在获取此路径之前应用虚拟属性[options.getters=true]«Boolean» 如果为 false,则跳过应用 Getter,只获取原始值
返回值
- «Any»
返回路径的值。
示例
// path
doc.get('age') // 47
// dynamic casting to a string
doc.get('age', String) // "47" Document.prototype.getChanges()
返回值
- «Object»
返回发生在文档上的更改,格式为将发送到 MongoDB 的格式。
示例
const userSchema = new Schema({
name: String,
age: Number,
country: String
});
const User = mongoose.model('User', userSchema);
const user = await User.create({
name: 'Hafez',
age: 25,
country: 'Egypt'
});
// returns an empty object, no changes happened yet
user.getChanges(); // { }
user.country = undefined;
user.age = 26;
user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
await user.save();
user.getChanges(); // { }修改 getChanges() 返回的对象不会影响文档的更改跟踪状态。即使您 delete user.getChanges().$set,Mongoose 仍然会向服务器发送 $set。
Document.prototype.id
类型
- «property»
参见
此文档的 _id 的字符串版本。
注意
此 Getter 默认存在于所有文档中。Getter 可以通过在构造时将 Schema 的 id 选项 设置为 false 来禁用。
new Schema({ name: String }, { id: false }); Document.prototype.init()
参数
doc«Object» MongoDB 返回的文档[opts]«Object»[fn]«Function»
Document.prototype.inspect()
返回值
- «String»
用于 console.log 的辅助函数
Document.prototype.invalidate()
参数
path«String» 要使无效的字段。对于数组元素,使用array.i.field语法,其中i是数组中从 0 开始的索引。err«String|Error» 指示path无效原因的错误val«Object|String|Number|any» 可选的无效值[kind]«String» 错误的可选kind属性
返回值
- «ValidationError» 当前的 ValidationError,包含所有当前无效的路径
将路径标记为无效,导致验证失败。
errorMsg 参数将成为 ValidationError 的消息。
value 参数(如果传递)将通过 ValidationError.value 属性提供。
doc.invalidate('size', 'must be less than 20', 14);
doc.validate(function (err) {
console.log(err)
// prints
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ size:
{ message: 'must be less than 20',
name: 'ValidatorError',
path: 'size',
type: 'user defined',
value: 14 } } }
}) Document.prototype.isDirectModified()
参数
[path]«String|Array[String]»
返回值
- «Boolean»
如果 path 被直接设置和修改,则返回 true,否则返回 false。
示例
doc.set('documents.0.title', 'changed');
doc.isDirectModified('documents.0.title') // true
doc.isDirectModified('documents') // false Document.prototype.isDirectSelected()
参数
path«String»
返回值
- «Boolean»
检查 path 是否被显式选择。如果没有投影,始终返回 true。
示例
Thing.findOne().select('nested.name').exec(function (err, doc) {
doc.isDirectSelected('nested.name') // true
doc.isDirectSelected('nested.otherName') // false
doc.isDirectSelected('nested') // false
}) Document.prototype.isInit()
参数
[path]«String»
返回值
- «Boolean»
检查 path 是否处于 init 状态,即它由 Document#init() 设置并且此后没有修改。
Document.prototype.isModified()
参数
[path]«String» 可选[options]«Object»[options.ignoreAtomics=false]«Boolean» 如果为 true,则如果路径位于使用原子操作(如push())修改的数组之下,则不返回 true
返回值
- «Boolean»
如果给定的任何路径被修改,则返回 true,否则返回 false。如果没有参数,则如果此文档中的任何路径被修改,则返回 true。
如果给出了 path,则检查路径或任何包含 path 作为其路径链一部分的完整路径是否被修改。
示例
doc.set('documents.0.title', 'changed');
doc.isModified() // true
doc.isModified('documents') // true
doc.isModified('documents.0.title') // true
doc.isModified('documents otherProp') // true
doc.isDirectModified('documents') // false Document.prototype.isNew
类型
- «property»
参见
$isNew 的旧别名。
Document.prototype.isSelected()
参数
path«String|Array[String]»
返回值
- «Boolean»
检查 path 是否在初始化此文档的源查询中被选中。
示例
const doc = await Thing.findOne().select('name');
doc.isSelected('name') // true
doc.isSelected('age') // false Document.prototype.markModified()
参数
path«String» 要标记为已修改的路径[scope]«Document» 要运行验证器的范围
将路径标记为有待写入数据库的更改。
在使用 Mixed 类型时非常有用。
示例
doc.mixed.type = 'changed';
doc.markModified('mixed.type');
doc.save() // changes to mixed.type are now persisted Document.prototype.modifiedPaths()
参数
[options]«Object»[options.includeChildren=false]«Boolean» 如果为 true,则还返回已修改路径的子节点。例如,如果为 false,则doc.colors = { primary: 'blue' };的已修改路径列表**将不包含**colors.primary。如果为 true,modifiedPaths()将返回包含colors.primary的数组。
返回值
- «Array[String]»
返回已修改的路径列表。
Document.prototype.overwrite()
参数
obj«Object» 要用其覆盖此文档的对象
返回值
- «Document» this
用 obj 的值覆盖此文档中的所有值,除了不可变属性。行为类似于 set(),除了它取消设置 obj 中不存在的所有属性。
Document.prototype.parent()
返回值
- «Document»
如果此文档是子文档或填充的文档,则返回文档的父级。如果没有父级,则返回原始文档。
Document.prototype.populate()
参数
path«String|Object|Array» 要填充的路径,或指定所有参数的对象,或两者之一的数组[select]«Object|String» 填充查询的字段选择[model]«Model» 要用于填充的模型。如果未指定,则填充将通过 Schema 的ref字段中的名称查找模型。[match]«Object» 填充查询的条件[options]«Object» 填充查询的选项(排序等)[options.path=null]«String» 要填充的路径。[options.populate=null]«string|PopulateOptions» 递归地填充填充文档中的路径。请参阅 深度填充文档。[options.retainNullValues=false]«boolean» 默认情况下,Mongoose 从填充的数组中删除 null 和 undefined 值。使用此选项使populate()保留null和undefined数组条目。[options.getters=false]«boolean» 如果为 true,Mongoose 将调用在localField上定义的任何 getter。默认情况下,Mongoose 获取localField的原始值。例如,如果您想 在您的localField上添加lowercasegetter,则需要将此选项设置为true。[options.clone=false]«boolean» 当您执行BlogPost.find().populate('author')时,具有相同作者的博客文章将共享author文档的 1 个副本。启用此选项以使 Mongoose 在分配之前克隆填充的文档。[options.match=null]«Object|Function» 在填充查询中添加其他过滤器。可以是包含 MongoDB 查询语法 的过滤器对象,或返回过滤器对象的函数。[options.transform=null]«Function» Mongoose 将在每个填充的文档上调用的函数,允许您转换填充的文档。[options.options=null]«Object» 其他选项,如limit和lean。[callback]«Function» 回调函数
返回值
- «Promise,null» 如果没有给出
callback,则返回 Promise。
参见
填充现有文档上的路径。
示例
// Given a document, `populate()` lets you pull in referenced docs
await doc.populate([
'stories',
{ path: 'fans', sort: { name: -1 } }
]);
doc.populated('stories'); // Array of ObjectIds
doc.stories[0].title; // 'Casino Royale'
doc.populated('fans'); // Array of ObjectIds
// If the referenced doc has been deleted, `populate()` will
// remove that entry from the array.
await Story.delete({ title: 'Casino Royale' });
await doc.populate('stories'); // Empty array
// You can also pass additional query options to `populate()`,
// like projections:
await doc.populate('fans', '-email');
doc.fans[0].email // undefined because of 2nd param `select` Document.prototype.populated()
参数
path«String»[val]«Any»[options]«Object»
返回值
- «Array,ObjectId,Number,Buffer,String,undefined,void»
获取在填充给定 path 期间使用的 _id(s)。
示例
const doc = await Model.findOne().populate('author');
console.log(doc.author.name); // Dr.Seuss
console.log(doc.populated('author')); // '5144cf8050f071d979c118a7'如果路径未填充,则返回 undefined。
Document.prototype.replaceOne()
参数
doc«Object»[options]«Object»[callback]«Function»
返回值
- «Query»
参见
Document.prototype.save()
参数
[options]«Object» 选项可选选项[options.safe]«Object» (已弃用)覆盖 模式的 safe 选项。使用w选项代替。[options.validateBeforeSave]«Boolean» 设置为 false 以在不验证的情况下保存。[options.validateModifiedOnly=false]«Boolean» 如果为true,Mongoose 将仅验证已修改的路径,而不是已修改的路径和required路径。[options.w]«Number|String» 设置 写入关注。覆盖 模式级writeConcern选项[options.j]«Boolean» 设置为 true 以使 MongoDB 在解决返回的 promise 之前等待此save()被 记录。覆盖 模式级writeConcern选项[options.wtimeout]«Number» 设置 写入关注的超时时间。覆盖 模式级writeConcern选项。[options.checkKeys=true]«Boolean» MongoDB 驱动程序默认情况下阻止您保存以 '$' 开头或包含 '.' 的键。将此选项设置为false以跳过该检查。请参阅 字段名称的限制[options.timestamps=true]«Boolean» 如果为false并且 时间戳 已启用,则跳过此save()的时间戳。[fn]«Function» 可选回调函数
返回值
- «Promise,undefined,void» 如果与回调函数一起使用,则返回 undefined,否则返回 Promise。
参见
通过将新文档插入数据库来保存此文档(如果 document.isNew 为 true),或者仅发送 updateOne 操作,其中包含对数据库的修改,在后一种情况下不会替换整个文档。
示例
product.sold = Date.now();
product = await product.save();如果保存成功,则返回的 promise 将使用已保存的文档来实现。
示例
const newProduct = await product.save();
newProduct === product; // true Document.prototype.schema
类型
- «property»
文档的模式。
Document.prototype.set()
参数
path«String|Object» 要设置的路径或键/值对对象val«Any» 要设置的值[type]«Schema|String|Number|Buffer|[object Object]» 可选地为“动态”属性指定类型[options]«Object» 可选地指定修改设置行为的选项
返回值
- «Document» this
设置一个或多个路径的值。.$set 的别名。
示例
// path, value
doc.set(path, value)
// object
doc.set({
path : value
, path2 : {
path : value
}
})
// on-the-fly cast to number
doc.set(path, value, Number)
// on-the-fly cast to string
doc.set(path, value, String)
// changing strict mode behavior
doc.set(path, value, { strict: false }); Document.prototype.toJSON()
参数
options«Object»[options.flattenMaps=true]«Boolean» 如果为 true,则将 Maps 转换为 POJO。如果您想要JSON.stringify()结果,则此选项很有用。[options.flattenObjectIds=false]«Boolean» 如果为 true,则将结果中的任何 ObjectId 转换为 24 个字符的十六进制字符串。
返回值
- «Object»
参见
此方法的返回值用于调用 JSON.stringify(doc)。
此方法接受与 Document#toObject 相同的选项。要默认将选项应用于模式的每个文档,请将 模式 的 toJSON 选项设置为相同的参数。
schema.set('toJSON', { virtuals: true });toJSON() 和 toObject() 选项之间有一个区别。当您调用 toJSON() 时,flattenMaps 选项 默认设置为 true,因为 JSON.stringify() 默认情况下不会将 maps 转换为对象。当您调用 toObject() 时,flattenMaps 选项默认设置为 false。
请参阅 模式选项,以获取有关设置 toJSON 选项默认值的更多信息。
Document.prototype.toObject()
参数
[options]«Object»[options.getters=false]«Boolean» 如果为 true,则应用所有 getter,包括虚拟属性[options.virtuals=false]«Boolean|Object» 如果为 true,则应用虚拟属性,包括别名。使用{ getters: true, virtuals: false }仅应用 getter,不应用虚拟属性。还可以使用{ pathsToSkip: ['someVirtual'] }形式的对象来省略特定的虚拟属性。[options.aliases=true]«Boolean» 如果options.virtuals = true,则可以设置options.aliases = false以跳过应用别名。如果options.virtuals = false,则此选项无效。[options.minimize=true]«Boolean» 如果为 true,则从输出中省略任何空对象[options.transform=null]«Function|null» 如果设置,Mongoose 将调用此函数以允许您转换返回的对象[options.depopulate=false]«Boolean» 如果为 true,则将任何传统填充的路径替换为输出中的原始 id。对虚拟填充的路径没有影响。[options.versionKey=true]«Boolean» 如果为 false,则从输出中排除版本键(默认情况下为__v)[options.flattenMaps=false]«Boolean» 如果为 true,则将 Maps 转换为 POJO。如果您想要JSON.stringify()toObject()的结果,则此选项很有用。[options.flattenObjectIds=false]«Boolean» 如果为 true,则将结果中的任何 ObjectId 转换为 24 个字符的十六进制字符串。[options.useProjection=false]«Boolean»- 如果为 true,则省略此文档的投影中排除的字段。除非您指定了投影,否则这将省略模式中
select: false的任何字段。
- 如果为 true,则省略此文档的投影中排除的字段。除非您指定了投影,否则这将省略模式中
返回值
- «Object» js 对象(不是 POJO)
参见
将此文档转换为普通的 JavaScript 对象 (POJO)。
缓冲区被转换为 mongodb.Binary 的实例以进行正确的存储。
获取器/虚拟属性
仅应用路径获取器的示例
doc.toObject({ getters: true, virtuals: false })仅应用虚拟获取器的示例
doc.toObject({ virtuals: true })应用路径和虚拟获取器的示例
doc.toObject({ getters: true })要将这些选项默认应用于模式的每个文档,请将您的 模式 toObject 选项设置为相同的参数。
schema.set('toObject', { virtuals: true })转换
我们可能需要根据某些条件对结果对象进行转换,例如删除一些敏感信息或返回自定义对象。在这种情况下,我们设置可选的 transform 函数。
转换函数接收三个参数
function (doc, ret, options) {}doc正在转换的 Mongoose 文档ret已转换的普通对象表示options使用中的选项(模式选项或内联传递的选项)
示例
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
doc.toObject(); // { name: 'Wreck-it Ralph' }通过转换,我们可以做更多的事情,不仅仅是删除属性。我们甚至可以返回完全新的自定义对象。
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
return { movie: ret.name }
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
doc.toObject(); // { movie: 'Wreck-it Ralph' }注意:如果转换函数返回 undefined,则返回值将被忽略。
转换也可以内联应用,覆盖模式选项中设置的任何转换。在 toObject 选项中指定的任何转换函数也会传播到任何子文档。
function deleteId(doc, ret, options) {
delete ret._id;
return ret;
}
const schema = mongoose.Schema({ name: String, docArr: [{ name: String }] });
const TestModel = mongoose.model('Test', schema);
const doc = new TestModel({ name: 'test', docArr: [{ name: 'test' }] });
// pass the transform as an inline option. Deletes `_id` property
// from both the top-level document and the subdocument.
const obj = doc.toObject({ transform: deleteId });
obj._id; // undefined
obj.docArr[0]._id; // undefined如果您想跳过转换,请使用 transform: false
schema.options.toObject.hide = '_id';
schema.options.toObject.transform = function (doc, ret, options) {
if (options.hide) {
options.hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }如果您在 toObject() 选项中传递转换,Mongoose 将除了顶层文档之外还将转换应用于 子文档。类似地,transform: false 会跳过所有子文档的转换。请注意,此行为与在模式中定义的转换不同:如果您在 schema.options.toObject.transform 中定义转换,则该转换将 **不会** 应用于子文档。
const memberSchema = new Schema({ name: String, email: String });
const groupSchema = new Schema({ members: [memberSchema], name: String, email });
const Group = mongoose.model('Group', groupSchema);
const doc = new Group({
name: 'Engineering',
email: 'dev@mongoosejs.io',
members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
});
// Removes `email` from both top-level document **and** array elements
// { name: 'Engineering', members: [{ name: 'Val' }] }
doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });转换,就像所有这些选项一样,也适用于 toJSON。查看 此 JSON.stringify() 指南,了解 toJSON() 和 toObject() 是为什么是单独的函数。
有关更多详细信息,请查看 模式选项。
在保存期间,在文档发送到数据库之前不会对其应用任何自定义选项。
Document.prototype.toString()
返回值
- «String»
用于 console.log 的辅助函数
Document.prototype.unmarkModified()
参数
path«String» 要取消标记修改的路径
清除指定路径上的修改状态。
示例
doc.foo = 'bar';
doc.unmarkModified('foo');
doc.save(); // changes to foo will not be persisted Document.prototype.updateOne()
参数
doc«Object»[options]«Object» 可选,请参见Query.prototype.setOptions()[options.lean]«Object» 如果为真,Mongoose 将返回文档作为普通 JavaScript 对象,而不是 Mongoose 文档。请参见Query.lean()和 Mongoose lean 教程。[options.strict]«Boolean|String» 覆盖模式的 严格模式选项[options.timestamps=null]«Boolean» 如果设置为false并且 模式级时间戳 已启用,则跳过此更新的时间戳。请注意,这允许您覆盖时间戳。如果模式级时间戳未设置,则不会执行任何操作。[callback]«Function»
返回值
- «Query»
参见
使用此文档 _id 作为查询选择器发送 updateOne 命令。
示例
weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);有效选项
- 与 Model.updateOne 中的相同
Document.prototype.validate()
参数
[pathsToValidate]«Array|String» 要验证的路径列表。如果设置,Mongoose 将仅验证给定列表中修改过的路径。[options]«Object» 内部选项[options.validateModifiedOnly=false]«Boolean» 如果为true,Mongoose 仅验证修改过的路径。[options.pathsToSkip]«Array|string» 要跳过的路径列表。如果设置,Mongoose 将验证不在此列表中的所有修改过的路径。
返回值
- «Promise» 返回一个 Promise。
执行为此文档注册的验证规则。
注意
此方法在 pre 保存时被调用,如果验证规则被违反,保存 将中止并抛出错误。
示例
await doc.validate({ validateModifiedOnly: false, pathsToSkip: ['name', 'email']}); Document.prototype.validateSync()
参数
[pathsToValidate]«Array|string» 仅验证给定的路径[options]«Object» 验证选项[options.validateModifiedOnly=false]«Boolean» 如果为true,Mongoose 将仅验证已修改的路径,而不是已修改的路径和required路径。[options.pathsToSkip]«Array|string» 要跳过的路径列表。如果设置,Mongoose 将验证不在此列表中的所有修改过的路径。
返回值
- «ValidationError,undefined,void» 如果验证过程中存在错误,则为 ValidationError;如果不存在错误,则为 undefined。

