What is the best way to verify a list in a MongoDB schema?

I am currently working on a home collection validation project that involves different room types (double, single, ensuite). The validation process should allow for the addition of all the listed room types.

"rooms.type": {bsonType: ["ensuite", "double", "single"]},

This is the validation schema that I have implemented:

db.createCollection("home", { 
validator : {
    $jsonSchema : {
    bsonType: "object",
    required: ["address.line1", "address.town", "rooms.type", 
    "rooms.qty", "rooms.price"],
 properties: {
    "address.line1": {bsonType: "string"},
    "address.town": {bsonType: "string"},
    "rooms.type": {bsonType: ["ensuite", "double", "single"]},
    "rooms.qty": {bsonType: "int", minimum: 0},
    "rooms.price": {bsonType: ["double"], minimum: 0},
}}}})

However, I encountered an error:

"ok" : 0,
"errmsg" : "Unknown type name alias: ensuite",
"code" : 2,
"codeName" : "BadValue"

I am looking to resolve this issue and ensure that the array room.type can accommodate any one or all attributes within the specified group in the schema.

Answer №1

If you want to define the data type of rooms.type as an array with at least one item, and each item in the array must be one of the following enums:

"rooms.type": {
    type: "array",
    minItems: 1,
    items: {
        enum: ["ensuite", "double", "single"]
    }
}

For more information on using $jsonSchema in MongoDB, you can refer to their official documentation. Additionally, you can explore the JSON Schema validation specification linked in the MongoDB documentation for more in-depth details.

Answer №2

To specify the schema in a different manner, you can use the following approach:

db.createCollection('home', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['address', 'rooms'],
      properties: {
        address: {
          bsonType: 'object',
          additionalProperties: false,
          required: ['line1', 'town'],
          properties: {
            line1: {
              bsonType: 'string'
            },
            town: {
              bsonType: 'string'
            }
          }
        },
        rooms: {
          bsonType: 'object',
          additionalProperties: false,
          required: ['type', 'qty', 'price'],
          properties: {
            type: {
              bsonType: 'string',
              enum: ["ensuite", "double", "single"]
            },
            qty: {
              bsonType: 'int',
              minimum: 0
            },
            price: {
              bsonType: 'array',
              items: {
                bsonType: 'double',
                minimum: 0
              }
            }
          }
        }
      }
    }
  }
});

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

Examining an array to identify palindromes

Is there a way to loop through an array and check if each word is a palindrome, instead of manually passing an argument for each word? If a word is a palindrome, return the word; otherwise, return 0. var myArray = ['viicc', 'cecarar', ...

Increasing the margin-left automatically in Bootstrap 3.0.0

I am looking to automatically generate margin-left in the ".card" class "style" element every time a post is entered on a page. My jQuery version is 1.12.4 This is my idea: If the .card CSS style has a margin-left of 0 and width of 479px, set position to ...

Encountering problems during the installation of Ionic - Error code 'EPROTO'

After attempting to install Ionic on my system, I encountered the following error message: npm ERR! code EPROTO npm ERR! errno EPROTO npm ERR! request to https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz failed, reason: write EPROTO 0:er ...

Troubleshooting: Images not displaying on webpage due to Ajax, JQuery, and JavaScript integration

I'm currently working on building a dynamic photo gallery using Ajax and JQuery in Javascript. I have set up a directory named "images" in Visual Studio Code and it contains my selection of 5 images. However, when I click the "next" and "previous" but ...

How can you display a set of components in React using TypeScript?

I'm currently working on rendering an array of JSX Components. I've identified two possible methods to achieve this. Method one (current approach): Create the array as an object type that stores the component properties and then build the JSX co ...

Ensure all <li> tags within a HTML document exhibit consistent jquery mousedown and hover effects, abstaining from the assignment of unique IDs to each

I understand that this approach might not be correct, but I wanted to create a simulation of what I am trying to achieve. Is there a way for each <li> element within a specific <ul class="myul"> to have separate mousedown, mouseout, hover effe ...

Encountering a "args" property undefined error when compiling a .ts file in Visual Studio Code IDE

I've created a tsconfig.json file with the following content: { "compilerOptions": { "target": "es5" } } In my HelloWorld.ts file, I have the following code: function SayHello() { let x = "Hello World!"; alert(x); } However ...

Change not accepted

I am a beginner in Angular and still grappling with the fundamentals. On my menu, I have a cart icon with an initial value of 0 upon first load. In my product list, each product has an 'AddToCart' button. What I aim to achieve is- I want to dy ...

How to showcase Twitter Track API on a website

const twitterRequest = twitter_oauth.post( "https://stream.twitter.com/1.1/statuses/filter.json?track=twitter", access_token, access_token_secret Hello, I have successfully implemented a track to display all the latest tweets containing the word "Twitter" ...

Showing findings from the search conducted

Recently, I've been experimenting with GSON and JSON to develop a search function that can display results. Although I have the following code snippet, I'm struggling to showcase the results: public static void main(String args[]) throws IOExcep ...

Is there a way to retrieve $httpProvider.defaults.xsrfCookieName within .factory?

Here's a question that might come from someone new to programming. I'm trying to avoid hard-coding the values for xsrfHeaderName and xsrfCookieName. Can anyone guide me on how to retrieve them from the $httpProvider? .factory('XSRFIntercept ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

Swapping the image source using a Vue dropdown menu

Recently I started using Vue and decided to implement a dropdown menu component (). The component pulls its list items from a JSON array structured as follows: <template> <div id="app"> <div id='container'> ...

Utilize an object model property as an array key for filtering in the AngularJS and MEANJS framework

I am currently working on a MEANJS application that includes a CRUD module for countries. When I select a country from the default list view, it redirects me to the view-country.client.view page. In order to enhance my model, I have introduced a field name ...

Tips for integrating React into a jQuery-centric web application?

After diving into React, I'm eager to showcase my skills by implementing it on select pages as a proof-of-concept for my supervisor at work. Can anyone guide me on how to achieve this using traditional script tags instead of imports? So far, I'v ...

There are no leaks displayed in Chrome Dev Tools, however, the Task Manager will show them until Chrome eventually crashes

Do you have a CPU-intensive application that you're working on? Check it out here: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880 It involves a Canvas on which various elements are constantly being drawn. Here's the HTML ...

Retrieve an array of 16 elements using React in a TypeScript environment

Exploring the new React 16 feature to return array elements within the render method is throwing a TypeScript error stating "Property 'type' is missing in type 'Element[]'" const Elements: StatelessComponent<{}> = () => ([ & ...

Infinite scrolling with a dynamic background

Hi there, I am working on my website and trying to create a smooth transition between sections similar to the one demonstrated here:. The challenge I'm facing is that the backgrounds of my sections cannot be fixed; they need to have background-attachm ...

Maintaining the integrity of Jquery Tab even after refreshing the page is essential

I recently started using Jquery and encountered an issue with tab implementation. Whenever I refresh the page, it automatically directs me back to the initial tab setting. $(function() { var indicator = $('#indicator'), i ...

SMTPConnection._formatError experienced a connection timeout in Nodemailer

Our email server configuration using Nodemailer SMTP settings looked like this: host: example.host port: 25 pool: true maxConnections: 2 authMethod: 'PLAIN' auth: user: 'username' pass: 'pass' We encou ...