Skip to main content

isDocument & isDocumentArray

isDocument

Typings:

function isDocument<T, S extends RefType>(doc: Ref<T, S> | null | undefined): doc is DocumentType<T>

Parameters:

NameTypeDescription
doc RequiredRef<T, S>The Document / Property to check

isDocument checks if the Input (doc) is a instance of mongoose.Model which makes it a Document.

Example

class Cat {
@prop({ ref: 'Cat' })
public partner: Ref<Cat>;

// this example could be smaller, but for demonstation purposes this is a longer version
public hasPartner(): boolean {
if (isDocument(this.partner)) {
// "this.partner" now has the type of "DocumentType<Cat>"
return true;
} else {
return false;
}
}
}
tip

Alternatively, since mongoose 6.4.0, $assertPopulated can also be used, but that function does not act as a type-guard only at runtime to actually check if a full path is populated.

isDocumentArray

Overload 1

Typings:

function isDocumentArray<T, S extends RefType>(
docs: mongoose.Types.Array<Ref<T, S>> | undefined
): docs is mongoose.Types.Array<DocumentType<NonNullable<T>>>;

Parameters:

NameTypeDescription
docs Requiredmongoose.Types.Array<Ref<T, S>>The Array to check all documents in

Overload 2

Typings:

function isDocumentArray<T, S extends RefType>(docs: Ref<T, S>[] | undefined): docs is DocumentType<NonNullable<T>>[];

Parameters:

NameTypeDescription
docs RequiredRef<T, S>[]The Array to check all documents in

Description

isDocumentArray checks if all the items in the given Array (docs) are a instance of mongoose.Model.
This function calls isDocument for each item in the array.
Only returns true if all items in the array return true.

Example

class Cat {
@prop({ ref: 'Cat' })
public kittens: Ref<Cat>;

// this example could be smaller, but for demonstation purposes this is a longer version
public areAllKittensExisting(): boolean {
if (isDocumentArray(this.kittens)) {
// "this.kittens" now has the type of "DocumentType<Cat>[]"
return true;
} else {
return false;
}
}
}