[SERVER-23912] validator can not validate array. Created: 25/Apr/16  Updated: 26/Apr/16  Resolved: 25/Apr/16

Status: Closed
Project: Core Server
Component/s: Storage
Affects Version/s: 3.2.5
Fix Version/s: None

Type: Bug Priority: Minor - P4
Reporter: tetsutaro watanabe Assignee: Kelsey Schubert
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Operating System: ALL
Participants:

 Description   

Hi.

I try to validate arry. But it does not work.

First I make collection with validator.

> db.createCollection("user" , {
...     validator : {
...          hoge : { $type : "array" }}})
{ "ok" : 1 }
 
> db.user.insert({"hoge":1})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})
 
# => This is correct
 
> db.user.insert({"hoge":[1,2,3]})
WriteResult({
        "nInserted" : 0,
        "writeError" : {
                "code" : 121,
                "errmsg" : "Document failed validation"
        }
})
 
# => This is wrong!



 Comments   
Comment by tetsutaro watanabe [ 26/Apr/16 ]

Hi Thomas,

Thank you ! I will use the workaround.

Comment by Kelsey Schubert [ 25/Apr/16 ]

Hi fetaro@gmail.com,

The behavior you describe is expected. As documented here, MongoDB evaluates the type of each element in the array. Since none of the elements in the array are arrays the validator rejects the document. I've included an example showing the same behavior using queries.

> db.user.insert({"hoge":1})
WriteResult({ "nInserted" : 1 })
> db.user.insert({"hoge":[1,2,3]})
WriteResult({ "nInserted" : 1 })
> db.user.find({ hoge : { $type : "array" }})
> db.user.find({ hoge : { $type : "double" }})
{ "_id" : ObjectId("571e790a8fd4cff897193c02"), "hoge" : 1 }
{ "_id" : ObjectId("571e79138fd4cff897193c03"), "hoge" : [ 1, 2, 3 ] }
> 

As a workaround please consider using the following validator:

db.createCollection("user" , { validator : { "hoge.0" : {$exists : true}}})

I expect that this validator will fit your use case, assuming that you do not intend to insert empty arrays or objects with a field name of "0".

Kind regards,
Thomas

Generated at Thu Feb 08 04:04:48 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.