<div class =“post-text”itemprop =“text”> 谢谢@ alex-blex的小费! 为新集合使用验证器: > db.createCollection(“places”, {validator: {“geometry.type”: {$in:… [“Point”, “MultiPoint”, “LineString”, “MultiLineString”, “Polygon”, “MultiPolygon”]… }}}){ “ok” : 1 }> db.places.createIndex({‘geometry’: ‘2dsphere’}){ “createdCollectionAutomatically” : false, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1}
</code>
现在我们无法插入空几何: > db.places.insert({‘geometry’: []})WriteResult({ “nInserted” : 0, “writeError” : { “code” : 121, “errmsg” : “Document failed validation” }})> db.places.insert({‘geometry’: {}})WriteResult({ “nInserted” : 0, “writeError” : { “code” : 121, “errmsg” : “Document failed validation” }})> db.places.insert({‘geometry’: null})WriteResult({ “nInserted” : 0, “writeError” : { “code” : 121, “errmsg” : “Document failed validation” }})
要将验证器添加到现有集合: > db.places.createIndex({‘geometry’: ‘2dsphere’}){ “createdCollectionAutomatically” : true, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1}> db.runCommand({ collMod: ‘places’, validator: {“geometry.type”: {$in:… [“Point”, “MultiPoint”, “LineString”, “MultiLineString”, “Polygon”, “MultiPolygon”]… }}}){ “ok” : 1 }