Data Models
Data models define the structure and schema of your data in jsonverse. When you create a data model, you specify the fields and their data types. This section explains how to define and work with data models.
1. Define Schema to use it:
To define a data model, create an object that describes the schema. Here’s an example:
const { jsonverse, Schema } = require("jsonverse");
const db = new jsonverse(); // using the default configuration options
In this example, we define a Schema class for using fields like username, email, age, and active. The data types (String, Number, Boolean) indicate the expected type of each field.
2. Define the Schema:
To work with a data model, you need to create an instance of it. Use the jsonverse API to create a model instance based on your schema:
const userSchema = new Schema({
name: "string",
email: "string",
password: "string",
});
const Users = db.model("Users", userSchema);
In this example, we create a schema instance for our User data model.
3. Data Operations with Models:
Once you have a model instance, you can perform various data operations like saving, updating, and querying data. Here are some common operations:
Save Data:
const newUser = { name: "John Doe", email: "john@example.com", password: "password", }; Users.save(newUser) .then((result) => { db.logSuccess(result); }) .catch((error) => { db.logError(error); });
Find Data by id:
Users.find(id) .then((result) => { db.logSuccess(result); }) .catch((error) => { db.logError(error); });
Find All Data:
Users.findAll() .then((result) => { db.logSuccess(result); }) .catch((error) => { db.logError(error); });
Update Data:
const updatedData = { name: "Johnathan Zac" }; Users.update(id, updatedData) .then((result) => { db.logSuccess(result); }) .catch((error) => { db.logError(error); });
Delete Data:
Users.delete(id) .then((result) => { db.logSuccess(result); }) .catch((error) => { db.logError(error); });
These operations allow you to interact with your data using the defined data model.
4. Data Validation:
jsonverse performs basic data validation based on your schema when saving data. If the data doesn’t match the schema, it will throw an error.
5. Model Usage:
You can use your defined data models across your application to ensure consistency in your data structure.
That’s the core concept of data models in jsonverse. They help you define and manage your data structure, making it easier to work with and ensuring data integrity.