4

Say I have a collection "cities" with the following documents:

Document 1:

{
    "_id": {
        "$oid": "5e00979d7c21388869c2c048"
    },
    "cityName": "New York"
}

Document 2:

{
    "_id": {
        "$oid": "5e00979d7c21388869c2c432"
    },
    "cityName": "Los Angeles"
}

and I want to create another collection "students" with the following document:

{
    "name": "John",
    "citiesVisited": [
        {
            "$ref": "cities",
            "$id": "5e00979d7c21388869c2c048"
        },
        {
            "$ref": "cities",
            "$id": "5e00979d7c21388869c2c432"
        }
    ]
}

How should the schema validation be? I tried the following validation:

validator = {
    "$jsonSchema": {
        "bsonType": "object",
        "required": ["name", "citiesVisited"],
        "properties": {
            "name": {
                    "bsonType": "string",
                    "description": "name of student."
            },
            "citiesVisited": {
                "bsonType": ["array"],
                "items": {
                    "bsonType": "object",
                    "required": ["$ref", "$id"],
                    "properties": {
                        "$ref": {
                                "bsonType": "string",
                            "description": "collection name"
                        },
                        "$id": {
                            "bsonType": "string",
                            "description": "document id of visited city"
                        }
                    }
                },
                "description": "cities visited by the student"
            }
        }
    }}

but it gives the following error when I try to get a list of all collections in the database:

bson.errors.InvalidBSON: collection must be an instance of str

I tried creating the validation without the "$" in "$ref" and "$id" and it worked fine but the document validation failed because of database references.

I want to use dbrefs when storing the cities.

0 Answers0