Database: Getting Started
Introduction
Almost every modern web application interacts with a database. Mongoloquent makes interacting with MongoDB databases extremely simple.
Configuration
You can configure Mongoloquent by creating a .env file in the root of your project. This file will contain the configuration settings for your MongoDB connection.
# default: mongodb://localhost:27017
MONGOLOQUENT_DATABASE_URI=mongodb://localhost:27017
# default: mongoloquent
MONGOLOQUENT_DATABASE_NAME=mongoloquent
# default: Asia/Jakarta
MONGOLOQUENT_TIMEZONE=Asia/Jakarta
Running SQL Queries
Once you have configured your database connection, you may run queries using the DB class. The DB class provides methods for each type of query: select, update, insert, and delete.
Running a Select Query
To run a basic SELECT query, you may use the collection method on the DB class:
- Typescript
- Javascript
import { DB, IMongoloquentSchema, IMongoloquentTimestamps } from 'mongoloquent';
interface IUser, extends IMongoloquentSchema, IMongoloquentTimestamps {
name: string;
}
const users = await DB.collection<IUser>("users").select("name").get();
for (const user of users) {
console.log(user.name);
}
import { DB } from 'mongoloquent';
const users = await DB.collection("users").select("name").get();
for (const user of users) {
console.log(user.name);
}
Running an Insert Statement
To execute an insert statement, you may use the insert method on the DB class.
- Typescript
- Javascript
import { DB, IMongoloquentSchema, IMongoloquentTimestamps } from 'mongoloquent';
interface IUser extends IMongoloquentSchema, IMongoloquentTimestamps {
name: string;
}
const user = await DB.collection<IUser>("users").insert({name: "John Doe"})
console.log(user);
import { DB } from 'mongoloquent';
const user = await DB.collection("users").insert({name: "John Doe"})
console.log(user);
Running an Update Statement
The update method should be used to update existing records in the database.
- Typescript
- Javascript
import { DB, IMongoloquentSchema, IMongoloquentTimestamps } from 'mongoloquent';
interface IUser extends IMongoloquentSchema, IMongoloquentTimestamps {
name: string;
}
const user = await DB.collection<IUser>("users")
.where("name", "John Doe")
.update({name: "Jane Doe"})
console.log(user);
import { DB } from 'mongoloquent';
const user = await DB.collection("users")
.where("name", "John Doe")
.update({name: "Jane Doe"})
console.log(user);
Running a Delete Statement
The delete method should be used to delete records from the database. the number of rows affected will be returned by the method:
- Typescript
- Javascript
import { DB, IMongoloquentSchema, IMongoloquentTimestamps } from 'mongoloquent';
interface IUser extends IMongoloquentSchema, IMongoloquentTimestamps {
name: string;
}
const user = await DB.collection<IUser>("users")
.where("name", "John Doe")
.delete()
console.log(user);
import { DB } from 'mongoloquent';
const user = await DB.collection("users")
.where("name", "John Doe")
.delete()
console.log(user);
Using Multiple Database Connections
If your application using multiple connections, you may define each connection via the connection and database methods provided by the DB class.
- Typescript
- Javascript
import { DB, IMongoloquentSchema, IMongoloquentTimestamps } from 'mongoloquent';
interface IUser extends IMongoloquentSchema, IMongoloquentTimestamps {
name: string;
}
const users = await DB.connection("uri")
.database("databaseName")
.collection<IUser>("users")
.get();
console.log(user);
import { DB } from 'mongoloquent';
const users = await DB.connection("uri")
.database("databaseName")
.collection("users")
.get();
console.log(user);
Database Transactions
You may use the transaction method provided by the DB class to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown. If the closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method:
- Typescript
- Javascript
import { DB } from 'mongoloquent';
await DB.transaction(async (session) => {
await DB
.collection("users")
.where("name", "John Doe")
.update({ votes: 1 }, { session });
await DB
.collection("posts")
.where("title", "Hello World")
.delete({ session });
})
import { DB } from 'mongoloquent';
await DB.transaction(async (session) => {
await DB
.collection("users")
.where("name", "John Doe")
.update({ votes: 1 }, { session });
await DB
.collection("posts")
.where("title", "Hello World")
.delete({ session });
})
Custom Connection
You also can set the connection in the DB class when execute transaction.
- Typescript
- Javascript
import { DB } from 'mongoloquent';
await DB.connection("mongodb://localhost:27017").transaction(async (session) => {
await DB
.collection("users")
.where("name", "John Doe")
.update({ votes: 1 }, { session });
await DB
.collection("posts")
.where("title", "Hello World")
.delete({ session });
})
import { DB } from 'mongoloquent';
await DB.connection("mongodb://localhost:27017").transaction(async (session) => {
await DB
.collection("users")
.where("name", "John Doe")
.update({ votes: 1 }, { session });
await DB
.collection("posts")
.where("title", "Hello World")
.delete({ session });
})
The DB class's
transactiononly working in the sameconnectionanddatabase.
Handling Deadlocks
The transaction method accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown:
- Typescript
- Javascript
import { DB } from 'mongoloquent';
await DB.transaction(async (session) => {
await DB
.collection("users")
.where("name", "John Doe")
.update({ votes: 1 }, { session });
await DB
.collection("posts")
.where("title", "Hello World")
.delete({ session });
}, { retries: 5 })
import { DB } from 'mongoloquent';
await DB.transaction(async (session) => {
await DB
.collection("users")
.where("name", "John Doe")
.update({ votes: 1 }, { session });
await DB
.collection("posts")
.where("title", "Hello World")
.delete({ session });
}, { retries: 5 })
The DB class's transaction methods control the transactions for both the Mongoloquent query builder and ORM.
Support us
Mongoloquent is an MIT-licensed open source project. It can grow thanks to the support by these awesome people. If you'd like to join them, please read more here.
Sponsors
_
