1.1.0 • Published 7 years ago

adonis-lucid-mongodb v1.1.0

Weekly downloads
17
License
MIT
Repository
github
Last release
7 years ago

AdonisJS Lucid MongoDB

NB - WORK IN PROGRESS

Version js-standard-style Build Status Coverage Status Greenkeeper badge

:pray: This repository is base on adonis-lucid. This package only work with mongodb.

Breaking update

Version 2.x was published to npm with new name. Make sure you install correct version:

Adonis versionVersionName
3.x.x1.x.xadonis-lucid-mongodb
4.x.x2.x.xlucid-mongo

Adonis-lucid-mongodb is a mongo query builder and ODM for Adonis framework. It also has support for database migrations, seeds and factories as Adonis-lucid.

You can learn more about AdonisJS and all of its awesomeness on http://adonisjs.com :evergreen_tree:

You can see example here adonis-mongodb-boilerplate

Note: If you decided use this package you need replace all setting of adonis-lucid by this package. See install steps for more detail

Usage

The usage of LucidMongo is similar to Lucid

Official Documentation of Lucid here

Query

const users =  yield User.all()

const users =  yield User.where('name', 'peter').fetch()

const users =  yield User.where({name: 'peter'}).limit(10).skip(20).fetch()

const users =  yield User.where({or: [{gender: 'female', age: {gte: 20}}, {gender: 'male', age: {gte: 22}}]}).fetch()
const user =  yield User.where('name').eq('peter').where('age').gt(18).lte(60).sort('-age').first()

const users =  yield User.where({age: {gte: 18}}).sort({age: -1}).fetch()

const users =  yield User.where('age', '>=', 18).fetch()

const users =  yield User.where('age').gt(18).paginate(2, 100)

const users =  yield User.where(function() {
  this.where('age', '>=', 18)
}).fetch()


// to query geo near you need declare field type as geometry and add 2d or 2dsphere index in migration file
const images = yield Image.where({location: {near: {lat: 1, lng: 1}, maxDistance: 5000}}).fetch()

const images = yield Image.where({location: {nearSphere: {lat: 1, lng: 1}, maxDistance: 500}}).fetch()

More Documentation of mquery

Aggregation

  const count = yield Customer.count()

  const count = yield Customer.where({invited: {$exist: true}}).count('position')

  const max = yield Employee.max('age')

  const total = yield Employee.where(active, true).sum('salary', 'department_id')

  const avg = yield Employee.where(active, true).avg('salary', {department: 'department_id', role: '$role_id'})

Relations

This package support relations like adonis-lucid:

  • hasOne
  • belongsTo
  • hasMany
  • hasManyThrough
  • belongsToMany

More Documentation of adonis relationships

mongodb has no join query so this package has no query like: has, whereHas, doesntHave, whereDoesntHave

Addition relations

  1. morphMany: A model can belong to more than one other model, on a single association. For example, you might have a Picture model that belongs to either an Author model or a Reader model
class Author extends Model {

  pictures () {
    return this.morphMany('App/Model/Picture', 'pictureableType', 'pictureableId')
  }

}

class Reader extends Model {

  pictures () {
    return this.morphMany('App/Model/Picture', 'pictureableType', 'pictureableId')
  }

}

class Picture extends Model {

  imageable () {
    return this.morphTo('App/Model', 'pictureableType', 'pictureableId')
  }

}
  1. embedsOne: EmbedsOne is used to represent a model that embeds another model, for example, a Customer embeds one billingAddress.
class Customer extends Model {

  billingAddress () {
    return this.embedsOne('App/Model/Address', '_id', 'billingAddress')
  }

}
  1. embedsMany: Use an embedsMany relation to indicate that a model can embed many instances of another model. For example, a Customer can have multiple email addresses and each email address is a complex object that contains label and address.
class Customer extends Model {

  emails () {
    return this.embedsMany('App/Model/Email', '_id', 'emails')
  }

}
  1. referMany: Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)
class Bill extends Model {

  items () {
    return this.referMany('App/Model/Item', '_id', 'items')
  }

}

Query relationships

  const user = yield User.with('emails').find(1)

  const user = yield User.with('emails', 'phone').fetch()

  const user = yield User.with(['emails', 'phone']).fetch()

  const user = yield User.with({
    relation: 'familyMembers', 
    scope: {
        where: { verified: true }, 
        sort: '-age'
    }
  }).fetch()

  const user = yield User.with({
    relation: 'familyMembers', 
    scope: query => {
      query.where(active, true).where('age').lt(18)
    }
  }).fetch()

Query logging

To show query logs run this command:

  • Linux, MacOS DEBUG=mquery npm run dev
  • Windows setx DEBUG mquery && npm run dev

Migration

Current only support create, drop, rename collection and index

up () {

  this.create('articles', (collection) => {
    collection.index('title_index', {title: 1})
  })

  this.collection('users', (collection) => {
    collection.index('email_index', {email: 1}, {unique: true})
  })

  this.collection('image', (collection) => {
    collection.index('location_index', {location: '2dsphere'}, {'2dsphereIndexVersion': 2})
  })

  this.rename('articles', 'posts')

  this.create('posts', (collection) => {
    collection.dropIndex('title_index')
  })

  this.drop('articles', 'posts')
}

Field type

Type of mongodb.ObjectID The objectId fields will be converted to mongodb.ObjectID before save to db.

class Article extends LucidMongo {
  static get objectIdFields() { return ['_id', 'categoryId'] } //default return ['_id']
}

The where query conditions will be converted to objectId too

const article = yield Article.find('58ccb403f895502b84582c63')
const articles = yield Article.where({department_id: {in: ['58ccb403f895502b84582c63', '58ccb403f895502b84582c63']}}).fetch()

Type of date

class Staff extends LucidMongo {
  static get dateFields() { return ['dob'] }
}

The field declare as date will be converted to moment js object after get from db

const staff = yield Staff.first()
const yearAgo = staff.dob.fromNow()

You can set attribute of model as moment js object, field will be converted to date before save to db

staff.dob = moment(request.input('dob'))

The where query conditions will be converted to date too

const user = yield User.where({created_at: {gte: '2017-01-01'}}).fetch()

Date type is UTC timezone Type of geometry

class Image extends LucidMongo {
  static get geoFields() { return ['location'] }
}

When declare field type as geometry the field will be transformed to geoJSON type

const image = yield Image.create({
  fileName: fileName,
  location: {lat: 1, lng: 1}
})

Result:

{ "type" : "Point", "coordinates" : [ 1, 1 ] }

After get from db it will be retransformed to

{lat: 1, lng: 1}

Get the mongodb drive

You can get the instance of mongodb drive to execute raw query

  const Database = use('Database')
  const mongo = yield Database.connection('mongodb')
  const users = yield mongo.collection('users').find().toArray()
  const phone = yield mongo.collection('phones').findOne({userId: user._id})

More document about mongo drive here

Installation

To setup this package

$ npm i --save adonis-lucid-mongodb

and then register lucid providers inside the your bootstrap/app.js file. you should complete replace all setting of adonis-lucid with adonis-lucid-mongodb

const providers = [
  // ...
  // 'adonis-lucid/providers/DatabaseProvider',
  // 'adonis-lucid/providers/LucidMongoProvider',
  // 'adonis-lucid/providers/FactoryProvider'  
  'adonis-lucid-mongodb/providers/DatabaseProvider',
  'adonis-lucid-mongodb/providers/LucidMongoProvider',
  'adonis-lucid-mongodb/providers/FactoryProvider',
]

const aceProviders = [
  // ...
  // 'adonis-lucid/providers/CommandsProvider',
  // 'adonis-lucid/providers/MigrationsProvider',
  // 'adonis-lucid/providers/SchemaProvider',
  // 'adonis-lucid/providers/SeederProvider',  
  'adonis-lucid-mongodb/providers/CommandsProvider',
  'adonis-lucid-mongodb/providers/MigrationsProvider',
  'adonis-lucid-mongodb/providers/SchemaProvider',
  'adonis-lucid-mongodb/providers/SeederProvider',
]

setting up aliases inside bootstrap/app.js file.

const aliases = {
  Database: 'Adonis/Src/Database',
  Lucid: 'Adonis/Src/LucidMongo',
  Schema: 'Adonis/Src/Schema'
  Migrations: 'Adonis/Src/Migrations',
  Factory: 'Adonis/Src/Factory'
}

add config to config/database.js file

module.exports = {

  /*
  |--------------------------------------------------------------------------
  | Default Connection
  |--------------------------------------------------------------------------
  |
  | Connection defines the default connection settings to be used while
  | interacting with Mongodb databases.
  |
  */
  connection: Env.get('DB_CONNECTION', 'mongodb'),
  /*-------------------------------------------------------------------------*/

  mongodb: {
    client: 'mongodb',
    connection: {
      host: Env.get('DB_HOST', 'localhost'),
      port: Env.get('DB_PORT', 27017),
      user: Env.get('DB_USER', 'root'),
      password: Env.get('DB_PASSWORD', ''),
      database: Env.get('DB_DATABASE', 'adonis'),
      auth: {
        source: Env.get('DB_AUTH_SOURCE', ''),
        mechanism: Env.get('DB_AUTH_MECHANISM', '')
      }
    }
  }

}

Contribution Guidelines

In favor of active development we accept contributions for everyone. You can contribute by submitting a bug, creating pull requests or even improving documentation.

1.1.0

7 years ago

1.0.55

7 years ago

1.0.54

7 years ago

1.0.53

7 years ago

1.0.52

7 years ago

1.0.51

7 years ago

1.0.50

7 years ago

1.0.49

7 years ago

1.0.48

7 years ago

1.0.47

7 years ago

1.0.46

7 years ago

1.0.45

7 years ago

1.0.44

8 years ago

1.0.43

8 years ago

1.0.42

8 years ago

1.0.41

8 years ago

1.0.40

8 years ago

1.0.39

8 years ago

1.0.38

8 years ago

1.0.37

8 years ago

1.0.36

8 years ago

1.0.35

8 years ago

1.0.34

8 years ago

1.0.33

8 years ago

1.0.32

8 years ago

1.0.31

8 years ago

1.0.30

8 years ago

1.0.29

8 years ago

1.0.28

8 years ago

1.0.27

8 years ago

1.0.26

8 years ago

1.0.25

8 years ago

1.0.24

8 years ago

1.0.23

8 years ago

1.0.22

8 years ago

1.0.21

8 years ago

1.0.20

8 years ago

1.0.19

8 years ago

1.0.18

8 years ago

1.0.17

8 years ago

1.0.16

8 years ago

1.0.15

8 years ago

1.0.14

8 years ago

1.0.13

8 years ago

1.0.12

8 years ago

1.0.11

8 years ago

1.0.10

8 years ago

1.0.9

8 years ago

1.0.8

8 years ago

1.0.7

8 years ago

1.0.6

8 years ago

1.0.5

8 years ago

1.0.4

8 years ago

1.0.3

8 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago

0.11.5

8 years ago

0.11.4

8 years ago

0.11.3

8 years ago

0.11.2

8 years ago

0.11.1

8 years ago

0.11.0

8 years ago

0.10.8

8 years ago

0.10.7

8 years ago

0.10.6

8 years ago

0.10.5

8 years ago

0.10.4

8 years ago

0.10.3

8 years ago

0.10.2

8 years ago

0.10.1

8 years ago

0.10.0

8 years ago

0.9.2

8 years ago

0.9.1

8 years ago

0.9.0

8 years ago