• This repository has been archived on 11/Feb/2022
  • Stars
    star
    1,393
  • Rank 33,729 (Top 0.7 %)
  • Language
    JavaScript
  • Created almost 13 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🍹 MongoDB ODM for Node.js apps based on Redux




Lightweight and flexible MongoDB ODM for Node.js apps based on Redux.

Build Status Coverage Status

Features

Flexible

Mongorito is based on Redux, which opens the doors for customizing literally everything - from model's state (reducers) to the behavior of core methods, like set(), save() or find().

Each model instance has a separate Redux store, which ensures isolation between other models and easy extensibility.

No schemas

If MongoDB doesn't enforce schemas, why would Mongorito do? Enjoy the schema-free data management with Mongorito the same way you do in mongo console.

Lightweight

Mongorito is betting on 3rd-party plugins to deliver extra functionality to developers. Mongorito ships with a barebones model with basic get/set, save/remove and querying functionality and let's you be in control of what's included and what's not.

Mongorito is basically a tiny Redux-based application, which uses the official MongoDB driver and mquery for querying. Not that amount of lines are relevant when measuring complexity, but each file (module) is less than 300 lines. Check out the source code and see for yourself!

Quick overview

const {Database, Model} = require('mongorito');

const db = new Database('localhost/blog');
await db.connect();

class Post extends Model {}

db.register(Post);

const post = new Post({
	title: 'Steve Angello rocks',
	author: {
		name: 'Emma'
	}
});

await post.save();

post.set('author.name', 'Rick');
await post.save();

await db.disconnect();

Note: await won't work at top level, it's used to reduce the complexity of an example.

Installation

$ npm install --save mongorito

Contents

Connection

Mongorito exports several own classes, as well as a few properties from the MongoDB driver:

const {
	Database,
	Model,
	Timestamp,
	ObjectId,
	MinKey,
	MaxKey,
	DBRef,
	Long
} = require('mongorito');

Database and Model are Mongorito's own exports, all the other ones are exported straight from mongodb package for convenience. Normally, you'd need only Database, Model and ObjectId.

To connect, initialize a Database, which accepts a MongoDB connection string and an optional configuration which will be passed to mongodb's connect function.

To connect and disconnect use connect()/disconnect() methods. Both returns a Promise.

For convenience, await will be used in all examples below, even though it doesn't work at top level.

const {Database, Model} = require('mongorito');

const db = new Database('localhost/blog', {
	reconnectTries: 5
});

await db.connect();
await db.disconnect();

You don't have to wait until connection establishes to perform operations. Mongorito automatically executes pending operations once connection is up.

Models

Creating a model

Model is the connection between your data and a database. Each model represents a single collection. Model is a simple class, which doesn't even need to have any properties or methods.

class Post extends Model {}

For Post model to work and be aware of the database it's connected to, make sure to register it in the database we created earlier.

db.register(Post);

That's it, the Post model is good to go!

Working with fields

To create a new document, create an instance of Post model.

const post = new Post();

Model's constructor also accepts an object of fields to instantiate the document with:

const post = new Post({
	title: 'Great post',
	author: {
		name: 'Sarah'
	}
});

Note, documents can contain nested fields and even models, just like in MongoDB.

To get one or all fields from the post document, use a get() method.

const title = post.get('title');
//=> "Great post"

const author = post.get('author.name');
//=> "Sarah"

const data = post.get();
//=>
//  {
//    title: "Great post"
//    author: {
//      name: "Sarah"
//    }
//  }

Similarly, use set() to update fields:

// update fields one by one
post.set('title', 'Amazing post');
post.set('author.name', 'Monica');

// or all at once
post.set({
	title: 'Amazing post',
	author: {
		name: 'Monica'
	}
});

To remove a field, use unset():

// unset single fields
post.unset('title');
post.unset('author.name');

// or multiple fields at once
post.unset(['title', 'author.name']);

Saving or removing documents

To create or update documents, simply call save(). Even though Mongorito differentiates these two operations internally, you don't have to care about that! Mongorito also infers the collection name from the model, so the instances of the model Post will be saved to posts collection.

await post.save();

When a document is saved, an _id field is automatically added.

post.get('_id');
//=> ObjectId("5905cb6b543c3a50e03e810d")

To remove a document, use remove().

await post.remove();

To remove multiple documents, use remove() on the model itself with a query as an argument.

await Post.remove({good: false});

Incrementing fields

Mongorito also provides a handy increment() method to increment or decrement numerical fields:

const post = new Post({
	views: 0
});

await post.increment('views');

post.get('views');
//=> 1

You can also supply a value to increment a field by a specific amount.

await post.increment('views', 2);

post.get('views');
//=> 3

Multiple fields can be incremented at once, too.

const post = new Post({
	views: 10,
	comments: 10
});

await post.increment({
	views: 2,
	comments: 5
});

post.get('views');
//=> 12

post.get('comments');
//=> 15

Embedding other models

Just like MongoDB, Mongorito allows to effortlessly embed other models. They're transparently converted between JSON and Mongorito models.

To embed models, use embeds() method on the model itself to help Mongorito with the model serialization when saving/reading from the database. embeds() method accepts a field name, where the embedded document (or array of documents) resides.

Here's the quick overview on how it works. Note, that model registering via register() is skipped in the following example.

class Post extends Model {}
class Author extends Model {}
class Comment extends Model {}

Post.embeds('author', Author);
Post.embeds('comments', Comment);

const post = new Post({
	title: 'Great post',
	author: new Author({name: 'Steve'}),
	comments: [new Comment({body: 'Interesting!'})]
});

await post.save();

The above post will be saved to the database as:

{
	"title": "Great post",
	"author": {
		"name": "Steve"
	},
	"comments": [
		{
			"body": "Interesting!"
		}
	]
}

You can also just pass objects instead of model instances and Mongorito will take care of that too.

const post = new Post({
	title: 'Great post',
	author: {
		name: 'Steve'
	},
	comments: [{
		body: 'Interesting!'
	}]
});

When that document will be retrieved from the database next time, all embedded documents will be wrapped with their corresponding models.

const post = await Post.findOne();

const author = post.get('author');
//=> Author { name: "Steve" }

author.get('name');
//=> "Steve"

Configuration

Using a different collection name

In case you need to store documents in a custom collection, you can override the default one using collection() method.

class Post extends Model {
	collection() {
		return 'awesome_posts';
	}
}

Queries

Mongorito uses mquery to provide a simple and comfortable API for querying. It inherits all the methods from mquery with a few exceptions, which will be documented below. For documentation, please check out mquery's API - https://github.com/aheckmann/mquery.

Here's a quick overview of how querying works in Mongorito. All documents returned from queries are automatically wrapped into their models.

// find all posts
await Post.find();

// find all amazing posts
await Post.find({amazing: true});
await Post.where('amazing', true).find();

// find 5 recent posts
await Post
	.limit(5)
	.sort('created_at', 'desc')
	.find();

// find one post
await Post.findOne({incredible: 'yes'});

// count posts
await Post.count({super: false});

Plugins

Using plugins

To use a 3rd-party plugin, all you have to do is to call use() method.

const timestamps = require('mongorito-timestamps');

db.use(timestamps());

This will apply mongorito-timestamps to models registered after that.

If you want to apply the plugin to a specific model only, call it on the model itself.

Post.use(timestamps());

Writing plugins

A plugin is simply a function that accepts a model. A familiarity with Redux and its concepts will help you tremendously with writing plugins.

const myPlugin = model => {
	// do anything with model (Post, in this case)
};

Post.use(myPlugin);

Feel free to assign new methods to the model or instances, add new middleware, modify the model's state and anything that comes to your mind.

Extending model with new methods

Here's an example of adding a class method and an instance method to a Post model.

const extendPost = Post => {
	Post.findRecent = function () {
		return this
			.limit(5)
			.sort('created_at', 'desc')
			.find();
	};

	Post.prototype.makeAmazing = function () {
		this.set('amazing', true);
	};
};

Post.use(extendPost);

const post = new Post();
post.makeAmazing();
post.get('amazing');
//=> true

const posts = await Post.findRecent();
//=> [Post, Post, Post]

Modifying model's state

If you plugin needs to have its own state, you can modify the model's reducer using modifyReducer() method. It accepts a function, which receives the existing reducer shape as an argument and should return a new object with added reducers.

const customReducer = (state = null, action) => {
	// reducer code...
};

const extendReducer = model => {
	model.modifyReducer(reducer => {
		return {
			...reducer,
			customState: customReducer
		}
	});
};

Changing behavior using middleware

Middleware can be used to change or modify the behavior of model's operations. You can interact with everything, from get/set operations to queries.

To add plugin's custom middleware to the default middleware stack, return it from the plugin function.

const myPlugin = () => {
	return store => next => action => {
		// middleware code...
	};
};

Obviously, to detect what kind of action is being handled, you need to be aware of Mongorito's action types.

const {ActionTypes} = require('mongorito');

const myPlugin = () => {
	return store => next => action => {
		if (action.type === ActionTypes.SET) {
			// alter set() behavior
		}

		return next(action);
	};
};

Again, the middleware is identical to the middleware you're used to when writing apps with Redux. There are only 2 new properties added to the store:

  • model - instance of the model (document) the middleware is currently running in. If middleware is running at the model level (without instantiated model), it will be undefined.
  • modelClass - model class (Post, for example).

Here's an example on how to access all props of the store:

const myPlugin = () => {
	return ({getState, dispatch, model, modelClass}) => next => action => {
		// `getState()` and `dispatch()` are from Redux itself
		// `model` is `post`
		// `modelClass` is `Post`

		return next(action);
	};
};

Post.use(myPlugin);

const post = new Post();
await post.save();

For examples on how to write middleware, check out Mongorito's native ones - https://github.com/vadimdemedes/mongorito/tree/master/lib/middleware.

Migrating from legacy version

Connection

Before:

const mongorito = require('mongorito');

mongorito.connect('localhost/blog');

After:

const {Database} = require('mongorito');

const db = new Database('localhost/blog');
await db.connect();

License

MIT Β© Vadim Demedes

More Repositories

1

ink

🌈 React for interactive command-line apps
TypeScript
22,325
star
2

tailwind-rn

🦎 Use Tailwind CSS in React Native projects
JavaScript
3,991
star
3

pastel

🎨 Next.js-like framework for CLIs made with Ink
TypeScript
2,167
star
4

trevor

🚦 Your own mini Travis CI to run tests locally
JavaScript
2,125
star
5

gifi

watch GIFs while running npm install
JavaScript
1,025
star
6

draqula

πŸ§› GraphQL client for minimalistic React apps
JavaScript
777
star
7

pronto

⚑ The now.sh experience for databases
JavaScript
703
star
8

cancan

πŸ”‘ Pleasant authorization library for Node.js
JavaScript
621
star
9

ink-ui

πŸ’„ Ink-redible command-line interfaces made easy
TypeScript
573
star
10

dom-chef

πŸ” Build DOM elements using JSX automatically
TypeScript
488
star
11

lanterns

β›©Write Markdown and get a GraphQL API for querying them for free
JavaScript
355
star
12

google-images

Search for images using Google Images
JavaScript
300
star
13

ronin

Toolkit for killer CLI applications
JavaScript
299
star
14

reconciled

βš›οΈ Simple way to create a custom React renderer
JavaScript
219
star
15

import-jsx

Import and transpile JSX on the fly
JavaScript
176
star
16

excalidraw-ui

Collection of reusable UI elements for Excalidraw
157
star
17

create-ink-app

Generate a starter Ink app
JavaScript
153
star
18

ink-spinner

Spinner component for Ink
TypeScript
144
star
19

generator-micro-service

πŸ›« Yeoman generator to kick-start your microservice with `micro` and `ava`!
JavaScript
144
star
20

thememirror

🦚 Beautiful themes for CodeMirror
TypeScript
132
star
21

ink-text-input

Text input component for Ink
TypeScript
131
star
22

ink-select-input

Select input component for Ink
TypeScript
128
star
23

thumbbot

Create thumbnails from images, video, audio and web pages.
JavaScript
124
star
24

ink-testing-library

Utilities for testing Ink apps
TypeScript
100
star
25

npm-search

Electron app to search npm via node-modules.com
JavaScript
95
star
26

mailman

Send emails in a comfortable way via models.
JavaScript
89
star
27

crown

Roll out features gradually
JavaScript
83
star
28

sushi

Koa-like framework for CLI tools.
JavaScript
83
star
29

create-pastel-app

Generate a starter Pastel app
JavaScript
71
star
30

ohcrash-app

Front-end web app of OhCrash
JavaScript
70
star
31

switch-branch-cli

Switch git branches by their pull request title
JavaScript
68
star
32

cat-facts

Interesting cat facts
JavaScript
57
star
33

minimist-options

Clean and beautiful options for minimist
JavaScript
54
star
34

node-video-thumb

Extract thumbnails from a video. Requires ffmpeg.
JavaScript
52
star
35

ohcrash-client

πŸ’£ Node.js client to report errors to OhCrash microservice
JavaScript
49
star
36

yoga-layout-prebuilt

Prebuilt yoga-layout package
JavaScript
47
star
37

slack-voice-messages

Record voice messages inside Slack
JavaScript
44
star
38

ink-redux

Redux bindings for Ink
JavaScript
43
star
39

interactor

Organize logic into interactors
JavaScript
36
star
40

restie

JavaScript ORM that talks to RESTful interface, rather than database. For Node.js and browsers.
JavaScript
31
star
41

supertap

Generate TAP output
JavaScript
30
star
42

mocha-generators

Enable support for ES6 generators in Mocha tests
JavaScript
29
star
43

generator-ink-cli

Scaffold out a CLI based on Ink
JavaScript
25
star
44

refined-overcast

Browser extension that improves Overcast user interface
CSS
18
star
45

templato

One interface to many template engines for Node.js and browsers.
JavaScript
17
star
46

ohcrash

πŸ’£ Microservice to report errors directly to your repo's GitHub Issues
JavaScript
17
star
47

ink-password-input

Password input component for Ink
JavaScript
16
star
48

interaptor

Intercept HTTP requests for testing purposes.
JavaScript
15
star
49

memcacher

Adding tags functionality to memcached, without modifying it. For Node.js.
CoffeeScript
15
star
50

buble-register

BublΓ© require hook
JavaScript
14
star
51

AnsiEscapes

ANSI escape codes for manipulating the terminal
Swift
14
star
52

udp-balancer

Load balancer for UDP
JavaScript
14
star
53

route66

Rails-inspired router for Koa and Express
JavaScript
14
star
54

setup-tailwind-rn

Set up Tailwind CSS in React Native apps
JavaScript
13
star
55

awesome-print

Beautifully print your JavaScript objects
JavaScript
12
star
56

patch-console

Patch console methods to intercept output
TypeScript
12
star
57

bucket-app

Interactive readme for your projects
JavaScript
11
star
58

detect-gender

Detect gender from name using genderize.io API
JavaScript
10
star
59

leeroy-jenkins-cli

Let Leeroy Jenkins make your boring CLI life more fun
JavaScript
9
star
60

syslog-parse

Parse syslog-formatted messages
JavaScript
9
star
61

net-socket

Node.js' net.Socket that automatically reconnects, 100% same API
JavaScript
8
star
62

code-excerpt

Extract excerpts from a source code
JavaScript
8
star
63

env-name

Get environment description (node + browser)
JavaScript
8
star
64

object-to-map

Convert object to ES6 Map
JavaScript
7
star
65

tempdir

Create a temporary directory
JavaScript
7
star
66

env-info

Get environment info (node + browser)
JavaScript
7
star
67

co-bind

Function#bind for generator functions.
JavaScript
7
star
68

generator-ink-component

Scaffold out an Ink component
JavaScript
7
star
69

ghost-api

Unofficial API client for Ghost blogs
JavaScript
6
star
70

ip-hash

ip-hash balancing algorithm (based on round-robin)
JavaScript
6
star
71

object-to-array

Convert object to an array of arrays of keys and values
JavaScript
6
star
72

leeroy-jenkins

Let Leeroy Jenkins make your boring developer life more fun.
JavaScript
5
star
73

asking

Tiny utility for getting user input in CLI programs
JavaScript
5
star
74

mongorito-timestamps

Plugin to add "created" and "updated" timestamps to Mongorito models
JavaScript
5
star
75

goodness-squad

4
star
76

react-floating-label-input

Floating-label input component for React
HTML
4
star
77

search-issues

Search GitHub issues
JavaScript
4
star
78

tailwindcss-custom-variant

Tailwind plugin to add custom variants
JavaScript
4
star
79

install-script-cli

Generate bash scripts to install your CLI programs from npm
JavaScript
4
star
80

install-script

Generate install scripts for your CLIs
Shell
4
star
81

wait-for-enter

Wait until user presses Enter in Terminal
JavaScript
3
star
82

list-dir

List directory contents recursively
JavaScript
3
star
83

crown-redis-store

Redis store for Crown
JavaScript
3
star
84

git-to-github-url

Get GitHub URL for a git repository
JavaScript
3
star
85

darkmatter-sdk

Enhance Darkmatter integration with your Astro website
TypeScript
3
star
86

express-errors

Express middleware for displaying Rails-inspired error pages
JavaScript
3
star
87

convert-to-spaces

Convert tabs to spaces in a string
JavaScript
3
star
88

koa-errors

Koa middleware for displaying Rails-inspired error pages
JavaScript
2
star
89

ama

Ask Me Anything!
2
star
90

mustached

CLI tool to render Mustache templates with JSON as data input
Crystal
2
star
91

format-object

util.format with object instead of argument list
JavaScript
2
star
92

is-public-repo

Check if GitHub repository is public
JavaScript
2
star
93

astro-selfie

Astro integration to generate page screenshots to show as Open Graph images
TypeScript
2
star
94

test

Dockerfile
2
star
95

crown-memory-store

Memory store for Crown
JavaScript
2
star
96

convert-to-tabs

Convert spaces to tabs in a string
JavaScript
2
star
97

fake-exec

Fake child_process#exec output for testing
JavaScript
1
star
98

koa-log-requests

Customizable Koa middleware for logging requests in console
JavaScript
1
star
99

sushi-help

Help message middleware for Sushi
JavaScript
1
star
100

array-generators

Common array functions with support for generators (forEach, filter, map)
JavaScript
1
star