Skip to content

HasValidation

Specifies validation rules for documents in a collection.

To learn more about validation, see HasValidation.validator.

Inheritors

Properties

allOptions

@LowLevelApi
abstract val allOptions: List<Option>

The full list of options set on this container.

Specific options are usually searched using the option extension.

context

The context used to generate this expression.

Functions

accept

@LowLevelApi
@DangerousMongoApi
abstract override fun accept(node: BsonNode)

Adds a new node as a child of this one.

acceptAll

Adds any number of nodes into this one.

freeze

@LowLevelApi
abstract override fun freeze()

Makes this node immutable.

option

@LowLevelApi
inline fun <O : Option> Options.option(): O?

Accesses the value of a given Option.

For example, if we have a helper function that sets some default options, and we want to know what maximum limit it set, we can use:

collection.count(
    options = {
        println(option<LimitOption>()) // Will print an integer
    }
)

simplify

@LowLevelApi
abstract fun simplify(): BsonNode?

Returns a simplified (but equivalent) expression to the current expression.

toBson

Writes the result of simplifying to a new BsonDocument.

toString

abstract override fun toString(): String

JSON representation of this option.

validator

open fun validator(
    level: ValidationLevel = ValidationLevel.Strict, 
    action: ValidationAction = ValidationAction.Error, 
    validator: FilterQuery<Document>.() -> Unit
)

Specifies validation rules for a collection.

By default, MongoDB accepts any document even if it doesn't look like other documents in the same collection.

By declaring validation rules, MongoDB will reject inserts and updates that do not pass these rules, which can help ensure the collection isn't corrupted.

Example

For example, if we want to ensure all birth dates as stored as MongoDB's native BsonType.Datetime and never as a BsonType.String.

class User(
    val name: String,
    val age: Int,
    val birthdate: Instant,
)

users.create {
    validator {
        User::birthdate hasType BsonType.Datetime
    }
}

If we try to insert a document with a string birthdate, for example in an external migration script, MongoDB will reject it.

See also

writeTo

@LowLevelApi
abstract override fun writeTo(writer: BsonFieldWriter)

Writes the result of simplifying this expression into writer.