AJV - setting additionalProperties to false with special cases allowed

I have implemented ajv to validate my mongodb schemas.

{
  type: "object",
  properties: { target: { type: "string" }, budget: { type: "number" } },
  required: ["target", "budget"],
  additionalProperties: false,
}

The snippet above represents the ajv schema for a specific document in my database. With additionalProperties: false, no extra properties are permitted.

My concern is how can I define a group of exceptional additional properties that should be allowed?

Answer №1

When defining properties in your schema, any property that is not marked as required is considered optional. These optional properties will be validated if they exist, but will be ignored if missing during data validation.

For example, consider validating an object with an optional maybeValue property:

const Ajv = require("ajv");
const ajv = new Ajv();

const schema = {
  type: "object",
  properties: { 
    goal: { type: "string" },
    cost: { type: "number" }, 
    maybeValue: { type: "string" },
  },
  required: ["goal", "cost"], // maybeValue is optional
  additionalProperties: false,
};

const validate = ajv.compile(schema);

const valid = {
  goal: 'win',
  cost: 10,
};

// This schema is valid even though maybeValue is missing since it's optional
validate(valid);

const notValid = {
  goal: 'win',
  cost: 10,
  maybeValue: 10
};

// This schema is not valid because maybeValue is not a string
validate(notValid);

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

Is there a method to retrieve the email address after obtaining the authentication token in Keystone?

Hey there! I was wondering if anyone knows if it's possible to retrieve a user's email address using the REST API v2.0 provided by Keystone for authentication in my application. I have been looking through the API docs and noticed that you can ge ...

One-way communication between two clients using Socket.io

While working on a basic socket.io application using React and Express, I've encountered an issue where two clients are facing difficulties in sending data to each other. For instance: Player 1 connects to the server followed by Player 2. Player 1 ...

Enabling access to public pages using Passport.js and Express.js

I'm currently developing a web application that allows users to browse public pages such as login, signup, and blog. However, access to account details requires authentication. The application is built using express js with passport js for authenticat ...

Error encountered: MongoDB cast exception - nested subdocument

Check out this schema design: var messageSchema = new Schema({ receivers: [User], message: String, owner: { type: Schema.Types.ObjectId, ref: 'User' } }); var userSchema = new Schema({ name: String, photo: String }); var in ...

What's the best way to ensure that all other routes remain operational while one route is busy handling a large database insertion task?

Currently, I am working on a project using node.js with express framework and mysql with sequelize ORM. In this method, an API is utilized to retrieve a large amount of data which is then stored in a database table. The data is in CSV format and I am util ...

What is the best way to upload a local image using JavaScript for TensorFlow?

I am having trouble loading a data.jpg file to be used by tensorflow mobilenet. When I try to require the file normally, I encounter an error message: So, my question is how can I load an image in my JavaScript code for use? I have tried various methods of ...

A guide on integrating Swig templates with Express 4

I encountered an issue trying to utilize Swig templates with Express for Node.js. Whenever I attempt to render a view, the following error is thrown: Error: Failed to lookup view "index" in views directory It seems that the Swig templates are not being ...

Struggling with getting React to successfully fetch data from an Express API. Any suggestions on how

I am having trouble with my fetch call to the express API. Even though I receive a response status of 200, I am still getting the index.html instead of the JSON data I need. Here is an overview of my setup: package.json "version": "1.0.0&qu ...

Combining Multiple JSON APIs on One Page [Using Node.js]

Is there a way to retrieve data from two APIs ('url' and 'url_test') and display it on a single page ('index.ejs') using Nodejs and Express? I have tried implementing Async and Promise, but haven't found the right solutio ...

Troubleshooting: How to resolve the issue of "Error [ERR_HTTP_HEADERS_SENT]: Unable to set headers after they have been sent to the client"

* **> const PORT=8000 const express = require('express') const {v4:uuidv4}=require('uuid') const bcrypt =require('bcrypt') const jwt =require('jsonwebtoken') const cors=require('cors') const {MongoClie ...

Does Model.find() in MongoDB return an object or an array of objects?

const trips = await Trip.find() After using console.log(typeof trips), it displayed 'object' in the console log. However, when I used console.log(trips), it showed an array of objects. This has left me slightly puzzled about what is actually bei ...

Exploring the capabilities of require() in nodeJS

I'm wondering about the inner workings of the require() function in a nodeJS application. What exactly does require() return? Let's say I want to utilize two third-party packages: lodash and request. After installing these packages, my code mig ...

decoding JSON node in Android

I am new to Android development. I have written a request code in Node.js to retrieve data from a database table. When I test this using Postman, it returns the JSON data correctly. However, when I run the same code in Android Studio, the response is empty ...

Troubleshooting a problematic dependency in Angular with the ngx-favicon package

Could someone please clarify why I am encountering issues when trying to run npm install ngx-favicon? npm install ngx-favicon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi ...

Is there a way to store a JSON object retrieved from a promise object into a global variable?

var mongoose = require('mongoose'); var Schema = mongoose.Schema; const NewsAPI = require('newsapi'); const { response } = require('express'); const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590'); var cu ...

Updating fields in a MongoDB collection with identical names

I am seeking guidance on how to update all instances of 'list_price' within a complex collection like this: "cost_price" : 79.9, "list_price" : 189.9, "sale_price" : 189.9, "integrations" : { "erp" : { "mbm" : { "cost_pri ...

Even after installing npm3, the npm -v command continues to display version 2.x.x

As I delve into the world of Angular 2, I learned that it requires npm version 3.x.x. Despite installing npm3 with the command npm install -g npm3, when I check my npm version using npm -v, it still shows as 2.15.8. Strangely, running npm3 -v displays vers ...

Issue: ENOTDIR error when trying to generate PDF from HTML on a Mac OS

In my meteor app, I am utilizing [email protected] . When I call .create(), I encounter the following error. It was functioning correctly before but started generating this error after updating to Mac Sierra. However, it works fine on Ubuntu OS. W2 ...

Unleashing the Power of Node.js: A Step-by-Step Guide to Crafting

I am developing a console interface that prompts the user with questions and receives input through the console. Some questions require the user to provide a limited number of inputs. I have researched ways to obtain console input in node js, but I haven&a ...

The TypeScript datatype 'string | null' cannot be assigned to the datatype 'string'

Within this excerpt, I've encountered the following error: Type 'string | null' cannot be assigned to type 'string'. Type 'null' cannot be assigned to type 'string'. TS2322 async function FetchSpecificCoinBy ...