What could be causing the validation failure in my mongodb database?

I'm currently learning about mongodb, I have gone through the documentation and attempted to insert a document page with referenced id's of other documents, but unfortunately, my validation fails. Here are the schema validation rules I have defined:

db.createCollection("page", {
    capped: true,
    size: 4500000000,
        max: 6,
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: [ "title", "url", "elements" ],
            additionalProperties: false,
            properties: {
                title: {
                    bsonType: "object",
                    required: [ "content_id" ],
                    properties: {
                        content_id: {
                            bsonType: "objectId"
                        }
                    }
                },
                url: {
                    bsonType: "string"
                },
                elements: {
                    bsonType: "array",
                    items: {
                        bsonType: "object",
                        required: [ "order" , "element_id" ],
                        properties: {
                            order: {
                                bsonType: "int"
                            },
                            element_id: {
                                bsonType: "objectId"
                            }
                        }
                    }
                }
            }
        }
    }
});

I am attempting to insert the following data (where content and document already contain the necessary id's):

var page1 = ObjectId();

db.page.insertOne(
    {
        "_id": page1,
        "title": {
            "content_id": content5
        },
        "url": "/home",
        "elements": [
            {
                "order": 1,
                "element_id": element1
            },
            {
                "order": 2,
                "element_id": element2
            },
            {
                "order": 3,
                "element_id": element3
            },
            {
                "order": 4,
                "element_id": element4
            }
        ]
    }
);

Can anyone advise on why this is generating an error? I seem to be having trouble understanding where the issue lies. Is there something wrong with the schema based on what I'm trying to insert?

2020-04-07T18:55:35.513+0200 E  QUERY    [js] WriteError({
        "index" : 0,
        "code" : 121,
        "errmsg" : "Document failed validation",
        "op" : {
                "_id" : ObjectId("5e8c72698d808f037e6adede"),
                "title" : {
                        "content_id" : ObjectId("5e8c72128d808f037e6aded6")
                },
                "url" : "/home",
                "elements" : [
                        {
                                "order" : 1,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adeda")
                        },
                        {
                                "order" : 2,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adedb")
                        },
                        {
                                "order" : 3,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adedc")
                        },
                        {
                                "order" : 4,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adedd")
                        }
                ]
        }
}) :
WriteError({
        "index" : 0,
        "code" : 121,
        "errmsg" : "Document failed validation",
        "op" : {
                "_id" : ObjectId("5e8c72698d808f037e6adede"),
                "title" : {
                        "content_id" : ObjectId("5e8c72128d808f037e6aded6")
                },
                "url" : "/home",
                "elements" : [
                        {
                                "order" : 1,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adeda")
                        },
                        {
                                "order" : 2,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adedb")
                        },
                        {
                                "order" : 3,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adedc")
                        },
                        {
                                "order" : 4,
                                "element_id" : ObjectId("5e8c724d8d808f037e6adedd")
                        }
                ]
        }
})
WriteError@src/mongo/shell/bulk_api.js:458:48
mergeBatchResults@src/mongo/shell/bulk_api.js:855:49
executeBatch@src/mongo/shell/bulk_api.js:919:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1163:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:264:9
@(shell):1:1

Your insights are greatly appreciated.

Answer №1

After troubleshooting, I have identified the issue - it was caused by an additional rule in the Properties section. When set to false, the _id property must be included before data insertion because _id is considered as an extra property.

Furthermore, using "int" as a bsonType can lead to errors; it is advisable to use "number" instead.

With this modified validator rule, I am now able to successfully insert my data:

db.createCollection("page", {
    capped: true,
    size: 4500000000,
    max: 6,
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: [ "_id", "title", "url", "elements" ],
            additionalProperties: false,
            properties: {
                _id: {
                    bsonType: "objectId"
                },
                title: {
                    bsonType: "object",
                    required: [ "content_id" ],
                    properties: {
                        content_id: {
                            bsonType: "objectId"
                        }
                    }
                },
                url: {
                    bsonType: "string"
                },
                elements: {
                    bsonType: "array",
                    items: {
                        bsonType: "object",
                        required: [ "order" , "element_id" ],
                        properties: {
                            order: {
                                bsonType: "number"
                            },
                            element_id: {
                                bsonType: "objectId"
                            }
                        }
                    }
                }
            }
        }
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Toggle Switch effectively removes the CSS class when set to false, but fails to reapply the class when set to true

Implementing a toggle switch using Bootstrap5 to control the visibility of grid lines. The setup includes adding a class to display grid lines when the toggle is true, and removing the class to hide the lines when the toggle is false. However, the issue ar ...

Using jQuery dialog to load a form through AJAX and then submitting the form to the modal dialog

I have adapted pieces of code from various sources to create the following script. The links successfully load the edit form in a modal using ajax, but upon submitting the form, the entire page refreshes instead of just the modal. I am seeking a solution ...

Discovering a specific field in MongoDB, rather than the entire document: suggestions

In order to achieve the desired outcome similar to what is achieved by SELECT AGE FROM STUDENTS WHERE NAME="AYUSH"; I followed this approach var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient ...

Validating arrays in Laravel through iterations

I used JavaScript to send an array from my form, where the values are collected from various input fields and stored in a single variable. <input type="hidden" name="details" id="details"> JavaScript Code: document.querySelectorAll('form&apos ...

Array restricted to maximum of 1,001 keys when non-sequential keys are employed

From a database query, I retrieve two IDs: one being the table's unique primary key (temp_id) and the other not being unique (auto_id). The query returns 1,477 records. When I store these in an array and use var_dump() to display the array contents, ...

Creating sequential numbers using jQuery

Recently, I worked on a script (credit to Chyno Deluxe) that generates a list of menu items based on what is written in the input box. However, I now have a new requirement which involves generating a sequence of numbers to be added continuously. Here is ...

Guide on displaying the appropriate component in NextJs routes

Whenever I switch routes, I encounter an issue. While navigating between pages works fine, dynamic routes are not rendered correctly. In the routes, I have a folder called uw with a file named [table].js inside. For example, when I manually navigate to uw ...

What is the best way to remove this .click function?

My goal is to create a switch function where clicking the "on" button changes its CSS, and if the user then clicks on the "off" button, the CSS returns to normal. I also need the switch to default to the "on" position, but my attempts so far have been unsu ...

What is the best way to customize the label of each object in SerializeJSON?

For my current project, I am using ColdFusion's SerializeJSON() to generate JSON data. Here is the code snippet I have implemented so far: <cfset rows = [] /> <cfloop query="rsProducts"> <!--- Create a row struct. ---> < ...

Bring the element into view by scrolling horizontally

I am facing a challenge with a list of floated left divs inside another div. This inner block of divs can be hovered over to move it left and right. Each inner div, known as 'events', has class names that include a specific year. Additionally, t ...

Sorting numpy arrays in order to obtain arrays displaying their ranks

I have a set of 3D NumPy arrays representing n matrices with dimensions x,x. For instance, if n=3 and x=2, the data would look like this: matrices = np.array([[[2,8],[1,7]],[[3,1],[5,4]],[[9,6],[2,3]]] matrices array([[[2, 8], [1, 7]], [[ ...

Is Joi's existence a myth?

I've been using Joi for validation, and I've encountered a situation that I'm having trouble with. I have an object that sometimes includes an id field (for editing) and other times it doesn't (for creating). My goal is to validate tha ...

What are some ways to manipulate JSON data following a successful AJAX request?

I've been grappling with this issue for quite some time now, trying various methods without any success. I won't bore you with the details of my failed attempts, but instead, I'll show you the code I'm currently working with. Here' ...

Issue with variable creation within ng-repeat

After reading a question on StackOverflow about determining the number of filtered out elements, I wrote the following code in Angular: <input type="text" ng-model="query" placeholder="Enter query..."> <div ng-if="filteredData.length!=data.length ...

Prevent button from triggering within div when clicked

I've encountered a perplexing issue that has me stumped. Within a defined div, I have included a button. My goal is to have a function called when anything inside the div, excluding the button itself, is clicked. However, if the button is clicked, the ...

Changing unsigned characters to unsigned integers (arrays)

I am trying to create a function that can convert unsigned char data into unsigned int values and then store them in an array. However, I keep encountering the following error: "passing argument 1 of 'sprintf' from incompatible pointer type." ...

Pagination and sorting in Mongoose databases

I'm struggling with implementing pagination using Mongoose and NodeJs. In my collection, I utilize ids for pagination as follows: var limit = req.params.limit ? req.params.limit : 1; limit ++; if(req.params.start){ var start = mongoose.Type ...

I'm encountering a type error every time I attempt to render an EJS page. Could someone please take a look and help me troubleshoot?

Below is the index.js code: CODE HERE const express = require('express'); const app = express(); const path = require('path'); app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.use(ex ...

Creating a custom function for working with JSON arrays in MySQL is a valuable skill to have

Looking to create a new custom function for fetching JSON array data in MySQL Server 5.6. Despite being unable to update the MySQL version, I have tried all the functions recommended by Stack Overflow. The goal is to have my select query only fetch the val ...

Tips for retrieving JSON data within a snowflake stored procedure

In my Snowflake SQL stored procedure, I have a JSON object saved to a variable named json_object: {"level":1,"object":"OBJECT1","object_schema":"SCHEMA1","object_type":"TABLE"}, {" ...