All Projects → najs-framework → najs-eloquent

najs-framework / najs-eloquent

Licence: MIT License
Use Mongoose in Typescript with elegant syntax. Inspired by Laravel Eloquent. Works with Node JS.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to najs-eloquent

yelp-camp
A Node.js web application project from the Udemy course - The Web Developer Bootcamp by Colt Steele
Stars: ✭ 36 (+38.46%)
Mutual labels:  mongoose
express-api
Building a RESTful API with Express and MongoDB
Stars: ✭ 28 (+7.69%)
Mutual labels:  mongoose
mongoolia
Keep your mongoose schemas synced with Algolia
Stars: ✭ 58 (+123.08%)
Mutual labels:  mongoose
OpenBook-E-Commerce
An e-commerce progressive web application, built with mern stack. It has features like product buy, order management by admin, payment gateway, cart, checkout and lot more.
Stars: ✭ 53 (+103.85%)
Mutual labels:  mongoose
express-typescript-mongoose-starter
A starter for Node JS, Express, Typescript, Mongoose application
Stars: ✭ 22 (-15.38%)
Mutual labels:  mongoose
Pepaverse
Pepaverse is an open source social network build with nodejs, mongoDB, passportjs and socket.io
Stars: ✭ 16 (-38.46%)
Mutual labels:  mongoose
NodeExpressCRUD
Node, Express, Mongoose and MongoDB CRUD Web Application
Stars: ✭ 45 (+73.08%)
Mutual labels:  mongoose
timeoff-server
TimeOff is an application that allows companies' employees to set vacations before they begin taking their time off. Implemented in modern tech stack i.e. Node, Express, MongoDB.
Stars: ✭ 33 (+26.92%)
Mutual labels:  mongoose
React-Native-Chat-App
A simple chatting app built with React Native, Socket.io, ExpressJS and MongoDB. The server app provides APIs for authentication, message sending and receiving. In the client app React-Native-Gifted-Chat is used for the chat interface.
Stars: ✭ 22 (-15.38%)
Mutual labels:  mongoose
login push
vue+koa2+jwt实现单点登录 + todolist增删改查
Stars: ✭ 20 (-23.08%)
Mutual labels:  mongoose
boss
React+express+sock.io+mongodb build a boss
Stars: ✭ 25 (-3.85%)
Mutual labels:  mongoose
node-mongoose-setup
Nodejs MongoDB REST API Sarter
Stars: ✭ 48 (+84.62%)
Mutual labels:  mongoose
onurl
URL Shortener created w/ Next.js, TypeScript, Mongoose
Stars: ✭ 48 (+84.62%)
Mutual labels:  mongoose
nestjs-file-streaming
NestJS File Streaming With MongoDB
Stars: ✭ 28 (+7.69%)
Mutual labels:  mongoose
hiroki
create a REST api faster than ever
Stars: ✭ 13 (-50%)
Mutual labels:  mongoose
ThinkApp
Test your knowledge with any of the available topic this fun and free Champion Quiz Master App. Save your time and effort by saving your queries & its resolutions
Stars: ✭ 15 (-42.31%)
Mutual labels:  mongoose
server-next
😎 The next generation of RESTful API service and more for Mix Space, powered by @nestjs.
Stars: ✭ 43 (+65.38%)
Mutual labels:  mongoose
shopping-cart
A full-fledged package to build an e-commerce application for iOS and Android similar to Myntra/JackThreads. Available with beautiful design and necessary features along with screen for Dashboard and Mobile app. Build using React Native, Expo, React, GraphQL, Apollo Client, Node and MongoDB.
Stars: ✭ 64 (+146.15%)
Mutual labels:  mongoose
FlipED
A LMS built specifically for Thailand's Education 4.0 system.
Stars: ✭ 24 (-7.69%)
Mutual labels:  mongoose
InviteManagerMongoDB
The first InviteManager / Logger / Tracker with mongoDB for Discord.
Stars: ✭ 23 (-11.54%)
Mutual labels:  mongoose

najs-eloquent

ORM written in Typescript, inspired by Laravel Eloquent, supports Mongodb/Mongoose.

Travis Maintainability Coverage Status node version npm version npm downloads npm license PRs Welcome

Warning: This is a documentation for v0.4.x, if you are using v0.3.x please checkout readme for v0.3.x in here.

If you are Laravel Eloquent lover and want to use it in Node JS you will love Najs Eloquent. Najs Eloquent is Laravel Eloquent, written in Typescript.

Installation

Add najs-binding, najs-eloquent

yarn add najs-binding najs-eloquent

or

npm install najs-binding najs-eloquent

That's it.

Drivers

NajsEloquent runs with Memory driver by default that means all data is saved in memory. There are some available drivers that you can use

I'm writing detail documentation, please try the library and give me a hand if you can.

Quick Usage

I. Define a model

Simply create new class extends from a Model class

import { Model } from 'najs-eloquent'

export class User extends Model {
  // define a property belongs to User model
  email: string

  // define a class name which used for Dependency injection
  // (this feature provided by "najs-binding" package)
  getClassName() {
    return 'YourNamespace.User'
  }
}

// Register the User class
Model.register(User)

II. Querying

You can query entries from database via static Query or instance query via .newQuery().

Retrieve entries via static query

const result = await User.where('id', '>', 10).get()

Retrieve entries via instance query

const result = new User()
  .newQuery()
  .where('id', '>', 10)
  .get()

You can build grouped query via sub-query, like this

// a = 1 AND (b = 2 OR c = 3)
const result = await User.where('a', 1)
  .where(function(subQuery) {
    subQuery.where('b', 2).orWhere('c', 3)
  })
  .get()

All querying functions support auto-completed/auto-suggestion to help you prevent any typo mistake. If you are familiar with Laravel Query Builder you can start write query without learning anything.

III. ActiveRecord - Create, Update & Delete

Create new model

const user = new User()
user.email = '[email protected]'
await user.save()

Update a model

const user = await User.firstOrFail('id')
user.email = '[email protected]'
await user.save()

Delete a model

const user = await User.firstOrFail('id')
await user.delete()

// or you can use query builder
await User.where('id', 'deleted-id').delete()

IV. Accessors and Mutators

Accessors

You can define an accessor by getter or a function like Laravel Eloquent

// file: Accessor.ts
import { Model } from 'najs-eloquent'

export class User extends Model {
  get full_name() {
    return this.attributes['first_name'] + ' ' + this.attributes['last_name']
  }

  // Laravel Eloquent style, available for node > 6.x
  // If you define this function AND getter, this function will be skipped
  getFullNameAttribute() {
    return this.attributes['first_name'] + ' ' + this.attributes['last_name']
  }
}

Mutators

You can define a mutator by setter or a function like Laravel Eloquent

// file: Mutator.ts
import { Model } from 'najs-eloquent'

export class User extends Model {
  set full_name(value: any) {
    // ...
  }

  // Laravel Eloquent style, available for node > 6.x
  // If you define this function AND setter, this function will be skipped
  setFullNameAttribute(value: any) {
    // ...
  }
}

V. Settings Properties

fillable & guarded

Just like Laravel, you can define mass assignable fields by fillable or guarded property

export class User extends Model {
  protected fillable = ['email', 'username']

  // This way also works :)
  // static fillable = ['email', 'username']
}

Only defined properties in fillable can be filled with .fill()

const user = new User()
user.fill({ email: 'a', password: 'x' })

console.log(user.toObject()) // => { email: a }

You can skip fillable setting by using .forceFill()

visible & hidden

You can define serialized fields by visible or hidden property

export class User extends Model {
  protected fillable = ['email', 'username']
  protected hidden = ['password']

  // This way also works :)
  // static hidden = ['password']
}

When using .toObject() or .attributesToObject() the password field will be skipped

const user = new User()
user.forceFill({ email: 'a', password: 'x' })

console.log(user.toObject()) // => { email: a }

timestamps

You can simply define timestamps for models by changing static (or protected) variable named timestamps. By using this feature every time the model get saved, created_at and updated_at will updated automatically

export class User extends Model {
  protected timestamps = true

  // This way also works :)
  // static timestamps = true
}

By default, Najs Eloquent will create 2 fields named created_at and updated_at, you can custom the fields' name:

export class User extends Model {
  protected timestamps = { createdAt: 'created', updatedAt: 'updated' }

  // This way also works :)
  // static timestamps = { createdAt: 'created', updatedAt: 'updated' }
}

softDeletes

You can simply define soft deletes feature for models by changing static (or protected) variable named softDeletes.

export class User extends Model {
  protected softDeletes = true

  // This way also works :)
  // static softDeletes = true
}

By using this feature every time the model get deleted the data ind database not actually deleted, it update deleted_at from null to date object. You can custom the deleted_at field name:

export class User extends Model {
  protected softDeletes = { deletedAt: 'deleted' }

  // This way also works :)
  // static softDeletes = { deletedAt: 'deleted' }
}

With soft deletes model all retrieve operators like find() or get() automatically return non-deleted entries only, you can use .withTrashed() or .onlyTrashed() to receive deleted entries

const users = await User.withTrashed().get()

VI. Events

You can listen to events creating, created, saving, saved, updating, updated, deleting, deleted, restoring, restored by using .on() or just trigger for 1 event only by .once(). All event listener is async

const user = new User()
user.on('created', async function(createdModel: User) {
  // ...
})
user.email = '...'
user.save()

You can listen to global event like this

User.on('created', function(createdModel: any) {
  // ...
})

VII. Relationships

najs-eloquent supports HasOne, HasMany, ManyToMany, MorphOne and MorphMany relationships. This feature doesn't look like Laravel. We couldn't give the same name the data and relation in Typescript, then you have to separate it

import { Model, HasMany, BelongsTo } from 'najs-eloquent'

class User extends Model {
  // Define property "posts" which receive data from relation "postsRelation"
  posts: HasMany<Post>

  // Define property "postsRelation" which handle this relationship
  get postsRelation() {
    return this.defineRelation('posts').hasMany(Post)
  }
}

class Post extends Model {
  // define property which is foreign key and point to User model
  user_id: string

  // Inverse relation data property
  user: BelongsTo<User>

  // Define inverse relation
  get userRelation() {
    return this.defineRelation('user').belongsTo(User)
  }
}

So we can assign new Post to user like this

const post = new Post()
const user = new User()
user.postsRelation.associate(post)

// when you save the user model, post will be saved and associate to User automatically
await user.save()

// eager load posts when loading users
const result = await User.with('posts').firstOrFail()
console.log(result.posts) // a collection of posts belongs to current user

// lazy load posts from user
await user.postsRelation.lazyLoad()

// or just load relation, najs-eloquent uses eager loading if possible
await user.load('posts')

I'm writing detail documentation, please try the library and give me a hand if you can.

VIII. Factory

najs-eloquent has Factory feature which use chance as a faker:

import { Factory, factory } from 'najs-eloquent'
import { User } from 'somewhere...'

// define a factory for User model
Factory.define(User, function(faker, attributes) {
  return Object.assign(
    {
      email: faker.email()
    },
    attributes
  )
})

// create model and save to database by factory()
await factory(User).create()

// make model instance only by factory()
const fakeUser = factory(User).make()

// make 3 model instances by factory()
const fakeUsers = factory(User)
  .times(3)
  .make()

IX. Builtin classes

All classes you need to implement new driver are available in NajsEloquent object.

I'm writing detail documentation, please try the library and give me a hand if you can.

Contribute

PRs are welcomed to this project, and help is needed in order to keep up with the changes of Laravel Eloquent. If you want to improve the library, add functionality or improve the docs please feel free to submit a PR.

Sponsors

If you want to become a sponsor please let me know.

You can buy me a beer via Paypal or Patreon.

Thanks in advance!

License

MIT © Nhat Phan

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].