Skip to content
Documentation
Schema System

Schema System in verse.db

The schema system allows you to define structured data models for your database. By using schemas, you can enforce data types, validation rules, and default values. Let's walk through the process of setting up and using a schema.

Setting Up a New Schema

Create an External Schema File:

  • We recommend creating an external file for your schema and exporting it. This way, you can reuse the schema across different parts of your project.
  • Here's an example of setting up a schema for a users database:
/models/UserSchema.js
const { Schema, SchemaTypes } = require("verse.db");
const db = require("./Data/db.versedb");
 
const userSchemaFields = {
  name: { type: SchemaTypes.String, required: true, minlength: 2, maxlength: 50 },
  age: { type: SchemaTypes.Number, min: 18, max: 100 },
  active: { type: SchemaTypes.Boolean },
  hobbies: {
    type: SchemaTypes.Array,
    required: false,
    minlength: 1,
    maxlength: 5,
    schema: {
      stringField: { type: SchemaTypes.String },
      numberField: { type: SchemaTypes.Number }
    }
  },
  customField: {
    type: SchemaTypes.Custom,
    validate: (value: any) => typeof value === 'string' && value.length <= 10 || 'Custom field must be a string with length less than or equal to 10.'
  },
  unionField: {
    type: SchemaTypes.Union,
    schema: [SchemaTypes.String, SchemaTypes.Number],
  }
};
 
const UsersSchema = new Schema(userSchemaFields);
 
module.exports = db.model("Users", UsersSchema);

Using the Schema

Import and Use the Schema:

  • In your application code, import the schema you've defined.
  • The schema name becomes the data name, so you don't need to provide the data name explicitly in each function call.
  • For example:
index.js
const USERS = require("./models/userSchema.js");
 
USERS.load(); // Load data from the schema
USERS.add(newData); // Add new data to the schema database
USERS.update(query, newData); // Update data in the schema database
USERS.remove(query); // Remove data from the schema database
USERS.find(query); // Find data in the schema database
// You can use other normal adapter functions without typing the data name explicitly

Schema Field Types

Available Field Types:

  • The schema system provides various field types. You can specify them using either schemaType.String or "String" syntax.
  • Here are the available field types:
type FieldType =
  | (SchemaTypes.String | "String")
  | (SchemaTypes.Number | "Number")
  | (SchemaTypes.Boolean | "Boolean")
  | (SchemaTypes.Array | "Array")
  | (SchemaTypes.Object | "Object")
  | (SchemaTypes.Null | "Null")
  | (SchemaTypes.Enum | "Enum")
  | (SchemaTypes.Custom | "Custom")
  | (SchemaTypes.Union | "Union")
  | (SchemaTypes.Any | "Any");

Feel free to explore the schema system and tailor it to your specific data requirements! 🚀


VERSE.DB. Powered by JEDI Studio.