Skip to content

Commit 4cbcba6

Browse files
committed
docs: More detailed explanation of the behaviour of the oldDocs field in Mango VDUs
1 parent 145678e commit 4cbcba6

1 file changed

Lines changed: 71 additions & 1 deletion

File tree

src/docs/src/ddocs/ddocs.rst

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -955,7 +955,8 @@ To use Mango selectors for validation, the design document must have the
955955
containing the following fields:
956956
957957
* ``newDoc``: New version of document that will be stored.
958-
* ``oldDoc``: Previous version of document that is already stored.
958+
* ``oldDoc``: Previous version of document that is already stored; this field is
959+
absent if the doc is being created for the first time.
959960
960961
For example, to check that all docs contain a ``title`` which is a string, and a
961962
``year`` which is a number:
@@ -1012,3 +1013,72 @@ this design document:
10121013
}
10131014
}
10141015
}
1016+
1017+
By using the ``oldDoc`` field, we can create rules that say a document can only
1018+
be updated if it is currently in a certain state. For example, this rule would
1019+
enforce that only documents describing actors can be updated:
1020+
1021+
.. code-block:: json
1022+
1023+
{
1024+
"language": "query",
1025+
1026+
"validate_doc_update": {
1027+
"oldDoc": { "type": "actor" }
1028+
}
1029+
}
1030+
1031+
This also makes it so that no new documents can be created, because a write is
1032+
only accepted if a previous version of the doc already exists. To relax this
1033+
constraint, allow ``oldDoc`` not to exist:
1034+
1035+
.. code-block:: json
1036+
1037+
{
1038+
"language": "query",
1039+
1040+
"validate_doc_update": {
1041+
"oldDoc": {
1042+
"$or": [
1043+
{ "$exists": false },
1044+
{ "type": "actor" }
1045+
]
1046+
}
1047+
}
1048+
}
1049+
1050+
This validator will allow any new document creation, and updates to docs where
1051+
the ``type`` field is ``"actor"``. We can also have multiple rules for new
1052+
document states that depend on the current state, by combining ``$or`` with
1053+
several sets of ``{ oldDoc, newDoc }`` rules:
1054+
1055+
.. code-block:: json
1056+
1057+
{
1058+
"language": "query",
1059+
1060+
"validate_doc_update": {
1061+
"$or": [
1062+
// allow creation of docs with an acceptable type
1063+
{
1064+
"oldDoc": { "$exists": false },
1065+
"newDoc": {
1066+
"type": { "$in": ["movie", "actor"] }
1067+
}
1068+
},
1069+
// if a doc currently has "type": "actor", make sure its "movies"
1070+
// field is a non-empty list of strings
1071+
{
1072+
"oldDoc": { "type": "actor" },
1073+
"newDoc": {
1074+
"movies": {
1075+
"$type": "array",
1076+
"$not": { "$size": 0 },
1077+
"$allMatch": { "$type": "string" }
1078+
}
1079+
}
1080+
},
1081+
// etc.
1082+
]
1083+
}
1084+
}

0 commit comments

Comments
 (0)