文件


Document.prototype.$assertPopulated()

參數
  • path «String|Array[String]» 要檢查的路徑或路徑陣列。如果任何給定的路徑未填充,$assertPopulated 會拋出錯誤。

  • [values] «Object»$set() 的可選值。如果您想手動填充路徑並斷言該路徑在 1 次呼叫中已填充,這會很方便。

返回
  • «Document» 這個

如果給定的路徑未填充,則拋出錯誤

範例

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» 這個

清除文件的已修改路徑。

範例

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»

取得所有子文件 (使用 bfs)


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» 這個

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»

如果給定的路徑為 null 或僅包含空物件,則傳回 true。這有助於判斷此子文件是否會被 minimize 選項 移除。

範例

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; // false

save() 成功後,Mongoose 會立即將 $isNew 設定為 false。這表示 Mongoose 會在 post('save') hook 執行之前$isNew 設定為 false。在 post('save') hook 中,如果 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» 這個

將此文件的變更追蹤狀態還原為給定的快照。請注意,$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» 這個

為避免衝突,在內部使用 set() 的別名


Document.prototype.$timestamps()

參數
  • [value] «Boolean» 覆寫目前的工作階段

返回
  • «Document,boolean,undefined,void» 當用作 getter (沒有參數) 時,將會傳回一個布林值,指示時間戳記選項狀態,如果未設定,則會使用「undefined」,否則會傳回「this」

此文件在使用 save()bulkSave() 時是否會預設套用時間戳記的 getter/setter。

範例

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» 這個
請參閱

取得已填充的欄位,並將其傳回未填充的狀態。

範例

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 «字串»
  • [type] «Schema|字串|數字|緩衝區|[物件 物件]» 可選地指定即時屬性的類型

  • [options] «物件»
    • [options.virtuals=false] «布林值» 在取得此路徑之前套用虛擬屬性

    • [options.getters=true] «布林值» 如果為 false,則跳過套用 getter,僅取得原始值

返回
  • «任何»

傳回路徑的值。

範例

// path
doc.get('age') // 47

// dynamic casting to a string
doc.get('age', String) // "47"

Document.prototype.getChanges()

返回
  • «物件»

傳回文件中發生的變更,其格式將會傳送到 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 預設存在於所有文件中。可以在建構時將其 Schemaid 選項 設定為 false 來停用此 getter。

new Schema({ name: String }, { id: false });

Document.prototype.init()

參數
  • doc «物件» mongo 傳回的文件

  • [opts] «物件»
  • [fn] «函式»

初始化文件,不使用 setter 或標記任何已修改的內容。

在從 mongodb 傳回文件後,會在內部呼叫。通常,您需要自行呼叫此函數。

此函數會觸發 init 中介軟體。請注意,init 鉤子是同步的。


Document.prototype.inspect()

返回
  • «字串»

console.log 的輔助函式


Document.prototype.invalidate()

參數
  • path «字串» 要失效的欄位。對於陣列元素,請使用 array.i.field 語法,其中 i 是陣列中從 0 開始的索引。

  • err «字串|錯誤» 指出 path 無效原因的錯誤

  • val «物件|字串|數字|任何» 可選的無效值

  • [kind] «字串» 錯誤的可選 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] «字串|字串陣列»
返回
  • «Boolean»

如果 path 是直接設定且已修改,則傳回 true,否則傳回 false。

範例

doc.set('documents.0.title', 'changed');
doc.isDirectModified('documents.0.title') // true
doc.isDirectModified('documents') // false

Document.prototype.isDirectSelected()

參數
  • path «字串»
返回
  • «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] «字串» 可選

  • [options] «物件»
    • [options.ignoreAtomics=false] «布林值» 如果為 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 «字串|字串陣列»
返回
  • «Boolean»

檢查是否在初始化此文件的來源查詢中選取了 path

範例

const doc = await Thing.findOne().select('name');
doc.isSelected('name') // true
doc.isSelected('age')  // false

Document.prototype.markModified()

參數
  • path «字串» 要標記為已修改的路徑

  • [scope] «文件» 要執行驗證器的範圍

將路徑標記為有待寫入資料庫的變更。

當使用 混合類型時,非常有用。

範例

doc.mixed.type = 'changed';
doc.markModified('mixed.type');
doc.save() // changes to mixed.type are now persisted

Document.prototype.modifiedPaths()

參數
  • [options] «物件»
    • [options.includeChildren=false] «布林值» 如果為 true,則也會傳回已修改路徑的子系。例如,如果為 false,則 doc.colors = { primary: 'blue' }; 的已修改路徑清單將包含 colors.primary。如果為 true,則 modifiedPaths() 會傳回包含 colors.primary 的陣列。

返回
  • «Array[String]»

傳回已修改的路徑清單。


Document.prototype.overwrite()

參數
  • obj «物件» 要覆寫此文件的物件

返回
  • «Document» 這個

使用 obj 的值覆寫此文件中的所有值,但不可變的屬性除外。行為與 set() 類似,但它會取消設定所有不在 obj 中的屬性。


Document.prototype.parent()

返回
  • «Document»

如果此文件是子文件或已填入的文件,則傳回文件的父系。如果沒有父系,則傳回原始文件。


Document.prototype.populate()

參數
  • path «字串|物件|陣列» 要填入的路徑或指定所有參數的物件,或是這些的陣列

  • [select] «物件|字串» 填入查詢的欄位選取

  • [model] «模型» 您想要用於填入的模型。如果未指定,則填入會依據 Schema 的 ref 欄位中的名稱查閱模型。

  • [match] «物件» 填入查詢的條件

  • [options] «物件» 填入查詢的選項 (排序等)

    • [options.path=null] «字串» 要填入的路徑。

    • [options.populate=null] «字串|填入選項» 遞迴填入已填入文件中的路徑。請參閱 深度填入文件

    • [options.retainNullValues=false] «布林值» 預設情況下,Mongoose 會從填入的陣列中移除 null 和 undefined 值。使用此選項讓 populate() 保留 nullundefined 陣列項目。

    • [options.getters=false] «布林值» 如果為 true,Mongoose 會呼叫在 localField 上定義的任何 getter。預設情況下,Mongoose 會取得 localField 的原始值。例如,如果您想要lowercase getter 新增至您的 localField,則需要將此選項設定為 true

    • [options.clone=false] «布林值» 當您執行 BlogPost.find().populate('author') 時,具有相同作者的部落格文章將會共用 1 個 author 文件的副本。啟用此選項以讓 Mongoose 在指派已填入的文件之前先複製它們。

    • [options.match=null] «物件|函式» 將額外的篩選器新增至填入查詢。可以是包含 MongoDB 查詢語法的篩選器物件,或是傳回篩選器物件的函式。

    • [options.transform=null] «函式» Mongoose 將在每個填入的文件上呼叫的函式,可讓您轉換填入的文件。

    • [options.options=null] «物件» 其他選項,例如 limitlean

  • [callback] «函式» 回呼

返回
  • «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 «字串»
  • [val] «任何»
  • [options] «物件»
返回
  • «陣列,ObjectId,數字,緩衝區,字串,未定義,void»

取得在給定 path 的填入期間使用的 _id。

範例

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 «物件»
  • [options] «物件»
  • [callback] «函式»
返回
  • «查詢»
請參閱

傳送 replaceOne 命令,其中此文件 _id 作為查詢選取器。

有效的選項


Document.prototype.save()

參數
返回
  • «Promise,undefined,void» 如果與回呼一起使用,則傳回 undefined,否則傳回 Promise。
請參閱

如果 document.isNewtrue,則會透過將新文件插入資料庫來儲存此文件,否則會傳送對資料庫的修改 updateOne 操作,在後一種情況下不會取代整個文件。

範例

product.sold = Date.now();
product = await product.save();

如果儲存成功,則傳回的 promise 將會以儲存的文件完成。

範例

const newProduct = await product.save();
newProduct === product; // true

Document.prototype.schema

類型
  • «property»

文件的 schema。


Document.prototype.set()

參數
  • path «String|Object» 要設定的路徑或鍵/值物件

  • val «Any» 要設定的值

  • [type] «Schema|String|Number|Buffer|[object Object]» 選擇性地為「即時」屬性指定類型

  • [options] «Object» 選擇性地指定修改設定行為的選項

返回
  • «Document» 這個

設定路徑的值或多個路徑的值。別名為 .$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 «物件»
    • [options.flattenMaps=true] «Boolean» 如果為 true,則將 Map 轉換為 POJO。如果您想要對結果使用 JSON.stringify(),這會很有用。

    • [options.flattenObjectIds=false] «Boolean» 如果為 true,則將結果中的任何 ObjectIds 轉換為 24 個字元的十六進位字串。

返回
  • «物件»
請參閱

此方法的返回值會在呼叫 JSON.stringify(doc) 時使用。

此方法接受與 Document#toObject 相同的選項。若要預設將選項套用至您 schema 的每個 document,請將您的 schema toJSON 選項設定為相同的參數。

schema.set('toJSON', { virtuals: true });

toJSON()toObject() 選項之間有一個差異。當您呼叫 toJSON() 時,flattenMaps 選項預設為 true,因為 JSON.stringify() 預設不會將 map 轉換為物件。當您呼叫 toObject() 時,flattenMaps 選項預設為 false

請參閱schema 選項以取得更多關於設定 toJSON 選項預設值的資訊。


Document.prototype.toObject()

參數
  • [options] «物件»
    • [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,則將 Map 轉換為 POJO。如果您想要對 toObject() 的結果使用 JSON.stringify(),這會很有用。

    • [options.flattenObjectIds=false] «Boolean» 如果為 true,則將結果中的任何 ObjectIds 轉換為 24 個字元的十六進位字串。

    • [options.useProjection=false] «Boolean»
      • 如果為 true,則省略此 document 的 projection 中排除的欄位。除非您指定了 projection,否則這會省略 schema 中任何具有 select: false 的欄位。
返回
  • «Object» js 物件 (不是 POJO)
請參閱

將此 document 轉換為純 JavaScript 物件 (POJO)。

為了正確儲存,Buffer 會轉換為 mongodb.Binary 的實例。

Getter/虛擬屬性

僅套用路徑 getter 的範例

doc.toObject({ getters: true, virtuals: false })

僅套用虛擬屬性 getter 的範例

doc.toObject({ virtuals: true })

同時套用路徑 getter 和虛擬屬性 getter 的範例

doc.toObject({ getters: true })

若要預設將這些選項套用至您 schema 的每個 document,請將您的 schema toObject 選項設定為相同的參數。

schema.set('toObject', { virtuals: true })

轉換

我們可能需要根據某些條件對產生的物件執行轉換,例如刪除一些敏感資訊或傳回自訂物件。在這種情況下,我們設定可選的 transform 函式。

轉換函式接收三個參數

function (doc, ret, options) {}
  • doc 正在轉換的 mongoose document
  • ret 已轉換的純物件表示法
  • options 使用中的選項 (schema 選項或內聯傳遞的選項)

範例

// 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,則傳回值將被忽略。

轉換也可以內聯套用,覆寫 schema 選項中設定的任何轉換。在 toObject 選項中指定的任何轉換函式也會傳播到任何子 document。

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 會將轉換套用到頂級 document 以及 子 document。類似地,transform: false 會跳過所有子 document 的轉換。請注意,對於在 schema 中定義的轉換,此行為是不同的:如果您在 schema.options.toObject.transform 中定義轉換,則該轉換將 **不會** 套用到子 document。

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() 是獨立的函式。

請參閱schema 選項以取得更多詳細資訊。

在儲存期間,在將 document 送到資料庫之前,不會對 document 套用任何自訂選項。


Document.prototype.toString()

返回
  • «字串»

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 «物件»
  • [options] «Object» 可選,請參閱 Query.prototype.setOptions()

    • [options.lean] «Object» 如果為 truthy,mongoose 將傳回 document 作為純 JavaScript 物件,而不是 mongoose document。請參閱 Query.lean()Mongoose lean 教學

    • [options.timestamps=null] «Boolean» 如果設定為 false 並且啟用 schema 層級時間戳記,則跳過此更新的時間戳記。請注意,這允許您覆寫時間戳記。如果未設定 schema 層級時間戳記,則不會執行任何操作。

  • [callback] «函式»
返回
  • «查詢»
請參閱

傳送 updateOne 命令,並以此 document 的 _id 作為查詢選擇器。

範例

weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);

有效的選項


Document.prototype.validate()

參數
  • [pathsToValidate] «Array|String» 要驗證的路徑清單。如果設定,Mongoose 將僅驗證給定清單中已修改的路徑。

  • [options] «Object» 內部選項

    • [options.validateModifiedOnly=false] «Boolean» 如果為 true,mongoose 僅驗證已修改的路徑。

    • [options.pathsToSkip] «Array|string» 要跳過的路徑清單。如果設定,Mongoose 將驗證不在這個清單中的每個已修改路徑。

返回
  • «Promise» 傳回 Promise。

執行此 document 的已註冊驗證規則。

注意

此方法會在 pre 儲存時呼叫,如果違反驗證規則,則會中止 save 並擲回錯誤。

範例

await doc.validate({ validateModifiedOnly: false, pathsToSkip: ['name', 'email']});

Document.prototype.validateSync()

參數
  • [pathsToValidate] «Array|string» 僅驗證給定的路徑

  • [options] «Object» 驗證的選項

    • [options.validateModifiedOnly=false] «布林值» 如果為 true,Mongoose 將只驗證已修改的路徑,而不是已修改的路徑和 required 路徑。

    • [options.pathsToSkip] «Array|string» 要跳過的路徑清單。如果設定,Mongoose 將驗證不在這個清單中的每個已修改路徑。

返回
  • «ValidationError,undefined,void» 如果驗證期間發生錯誤,則為 ValidationError,如果沒有錯誤,則為 undefined。

執行此 document 的已註冊驗證規則 (跳過非同步驗證器)。

注意

如果您需要同步驗證,此方法會很有用。

範例

const err = doc.validateSync();
if (err) {
  handleError(err);
} else {
  // validation passed
}