ドキュメント
Document.prototype.$assertPopulated()
Document.prototype.$clearModifiedPaths()
Document.prototype.$clone()
Document.prototype.$createModifiedPathsSnapshot()
Document.prototype.$errors
Document.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.$isNew
Document.prototype.$locals
Document.prototype.$markValid()
Document.prototype.$op
Document.prototype.$parent()
Document.prototype.$populated()
Document.prototype.$restoreModifiedPathsSnapshot()
Document.prototype.$session()
Document.prototype.$set()
Document.prototype.$timestamps()
Document.prototype.$validate()
Document.prototype.$where
Document.prototype.depopulate()
Document.prototype.directModifiedPaths()
Document.prototype.equals()
Document.prototype.errors
Document.prototype.get()
Document.prototype.getChanges()
Document.prototype.id
Document.prototype.init()
Document.prototype.inspect()
Document.prototype.invalidate()
Document.prototype.isDirectModified()
Document.prototype.isDirectSelected()
Document.prototype.isInit()
Document.prototype.isModified()
Document.prototype.isNew
Document.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.schema
Document.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()
に設定する値。手動でパスをポピュレートし、そのパスが 1 回の呼び出しでポピュレートされたことをアサートする場合に便利です。
戻り値
- «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»
すべてのサブドキュメントを取得(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» this
path
の数値値を指定された val
で増分します。このドキュメントで save()
を呼び出すと、Mongoose は $set
ではなく $inc
を送信します。
例
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がこのドキュメントを削除されたと考えるかどうか。
ゲッター/セッター。ドキュメントが削除されたかどうかを判断します。
例
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 を返します。このサブドキュメントが 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
Mongoose は、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
は、親に $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»
このドキュメントに関連付けられたセッションの周りのゲッター/セッター。関連付けられたセッションを持つクエリから取得したドキュメントを 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» ゲッターとして使用する場合 (引数なし)、タイムスタンプオプションの状態を示すブール値が返されるか、設定されていない場合は "undefined" が使用されます。それ以外の場合は "this" が返されます
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 の場合、ゲッターの適用をスキップして、生の値をそのまま取得します
戻り値
- «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 の文字列バージョン。
注意
このゲッターは、デフォルトですべてのドキュメントに存在します。ゲッターは、構築時にSchema
のid
オプションをfalseに設定することで無効にできます。
new Schema({ name: String }, { id: false });
Document.prototype.init()
パラメータ
doc
«Object» mongoによって返されるドキュメント[opts]
«Object»[fn]
«Function»
セッターや変更のマークをせずにドキュメントを初期化します。
ドキュメントがmongodbから返された後、内部的に呼び出されます。通常、この関数を自分で呼び出す必要はありません。
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» バリデーターを実行するスコープ
パスを、dbに書き込む保留中の変更があるとしてマークします。
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» ポピュレーションに使用するモデル。指定しない場合、populateは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
で定義されたゲッターを呼び出します。デフォルトでは、MongooseはlocalField
の生の値を取得します。たとえば、lowercase
ゲッターをlocalField
に追加する場合は、このオプションを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を取得します。
例
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.session=null]
«Session» この保存操作に関連付けられたセッション。指定しない場合、デフォルトでドキュメントに関連付けられたセッションになります。[options.safe]
«Object»(非推奨)スキーマのsafeオプションを上書きします。代わりにw
オプションを使用してください。[options.validateBeforeSave]
«Boolean» 検証せずに保存するにはfalseに設定します。[options.validateModifiedOnly=false]
«Boolean»true
の場合、Mongooseは変更されたパスとrequired
パスではなく、変更されたパスのみを検証します。[options.w]
«Number|String» 書き込み保証を設定します。スキーマレベルのwriteConcern
オプションを上書きします[options.j]
«Boolean» MongoDBが、このsave()
がジャーナルに記録されてから、返されたPromiseを解決するまで待機する場合はtrueに設定します。スキーマレベルの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の場合、MapをPOJOに変換します。結果をJSON.stringify()
する場合に便利です。[options.flattenObjectIds=false]
«Boolean» trueの場合、結果のObjectIdを24文字の16進文字列に変換します。
戻り値
- «Object»
参照
このメソッドの戻り値は、JSON.stringify(doc)
の呼び出しで使用されます。
このメソッドは、Document#toObjectと同じオプションを受け入れます。スキーマのすべてのドキュメントにデフォルトでオプションを適用するには、スキーマのtoJSON
オプションを同じ引数に設定します。
schema.set('toJSON', { virtuals: true });
toJSON()
とtoObject()
のオプションには1つの違いがあります。toJSON()
を呼び出すと、flattenMaps
オプションがデフォルトでtrue
になります。これは、JSON.stringify()
がデフォルトでMapをオブジェクトに変換しないためです。toObject()
を呼び出すと、flattenMaps
オプションはデフォルトでfalse
になります。
toJSON
オプションのデフォルト設定の詳細については、スキーマオプションを参照してください。
Document.prototype.toObject()
パラメータ
[options]
«Object»[options.getters=false]
«Boolean» trueの場合、バーチャルを含め、すべてのゲッターを適用します[options.virtuals=false]
«Boolean|Object» trueの場合、エイリアスを含め、バーチャルを適用します。ゲッターのみを適用し、バーチャルを適用しない場合は、{ getters: true, virtuals: false }
を使用します。{ pathsToSkip: ['someVirtual'] }
形式のオブジェクトを使用して、特定のバーチャルを省略することもできます。[options.aliases=true]
«Boolean»options.virtuals = true
の場合、options.aliases = false
を設定して、エイリアスの適用をスキップできます。このオプションは、options.virtuals = false
の場合、no-opです。[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の場合、結果のObjectIdを24文字の16進文字列に変換します。[options.useProjection=false]
«Boolean»- true の場合、このドキュメントのプロジェクションで除外されているフィールドを省略します。プロジェクションを指定していない場合、スキーマで
select: false
が設定されているフィールドを省略します。
- true の場合、このドキュメントのプロジェクションで除外されているフィールドを省略します。プロジェクションを指定していない場合、スキーマで
戻り値
- «Object» JavaScript オブジェクト(POJO ではない)
参照
このドキュメントをプレーンな JavaScript オブジェクト(POJO)に変換します。
Buffer は、適切な保存のために mongodb.Binary のインスタンスに変換されます。
ゲッター/バーチャル
パスゲッターのみを適用する例
doc.toObject({ getters: true, virtuals: false })
バーチャルゲッターのみを適用する例
doc.toObject({ virtuals: true })
パスゲッターとバーチャルゲッターの両方を適用する例
doc.toObject({ getters: true })
これらのオプションをスキーマのすべてのドキュメントにデフォルトで適用するには、スキーマの toObject
オプションに同じ引数を設定します。
schema.set('toObject', { virtuals: true })
変換
機密情報を削除したり、カスタムオブジェクトを返したりするなど、何らかの基準に基づいて結果のオブジェクトを変換する必要がある場合があります。この場合、オプションの transform
関数を設定します。
変換関数は 3 つの引数を受け取ります。
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
でも利用できます。toJSON()
と toObject()
が別々の関数である理由については、この JSON.stringify()
ガイドを参照してください。
詳細については、スキーマオプションを参照してください。
保存中、カスタムオプションはデータベースに送信される前のドキュメントには適用されません。
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» truthy の場合、Mongoose はドキュメントを Mongoose ドキュメントではなく、プレーンな JavaScript オブジェクトとして返します。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
で呼び出され、検証ルールに違反した場合、save が中止され、エラーがスローされます。
例
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