MonarchORM

Quick Start

A brief guide to get you started with our library, covering setup and usage examples.

Installation

NPM:

  npm install monarch-orm

Or Yarn:

  yarn add monarch-orm

Or PNPM:

  pnpm add monarch-orm

Getting Started

To create a connection instance, you can use any database client of your choice and pass it to the createDatabase function. Alternatively, you can utilize the built-in createClient function to simplify the process.

const client = createClient('mongodb://localhost:27017')

Defining Schemas and connecting to the database

Use the createSchema function to define the structure of your model. Specify the fields and their types, using the available types and modifiers.

const UserSchema = createSchema("users", {
  name: string(),
  isVerified: boolean(),
});

Create a database instance using any client you deem fit and drop it into the createDatabase function

Or you can use the built-in createClient function.

Then you pass your schemas to the second arguement

const { collections } = createDatabase(client, {
  users: UserSchema,
});

Inserting Documents

You can insert new documents into your collection using the insert method. Ensure that the data conforms to the defined schema.

Example: Inserting a new user

const newUser = await collections.users
  .insert()
  .values({
    name: "Alice",
    email: "alice@example.com",
    age: 25,
    isVerified: true,
  })
  .exec();

Querying Documents

Retrieve documents from your collection using the find or findOne methods.

Example: Querying all users

const users = await collections.users.find().where({}).exec();
console.log(users);
 
// Or just...
const users = await collections.users.find({}).exec();
console.log(users);
 
 
// For finding one
 
const user = await collections.users.find().where({
  name: "Alice"
}).exec();
console.log(users);
 
// Or...
const user = await collections.users.findOne({
  name: "Alice"
}).exec();
console.log(users);

Updating Documents

Update documents in your collection using the update method. You can update a single document or multiple documents based on a filter.

Example: Updating a single user's email

const updatedUser = await collections.users
  .updateOne()
  .set({
    email: "alice.updated@example.com",
  })
  .where({
    name: "Alice",
  })
  .exec();
console.log(updatedUser);

Example: Updating multiple users' isVerified field

const updatedUsers = await collections.users
  .updateMany()
  .set({
    isVerified: true,
  })
  .where({
    isVerified: false,
  })
  .exec();
console.log(updatedUsers);

Note: The update method returns the number of documents updated.

Conclusion

That's the end of our quick start. As you continue building your application, you may want to explore more advanced features like:

Check out the rest of the documentation to learn more about these topics and other features available.

On this page