type-mongo-mapper
TypeScript icon, indicating that this package has built-in type declarations

0.0.6 • Public • Published

🔗 type-mongo-mapper

A @decorator based MongoDB document to ES6 class mapper.

travis codecov

type-mongo-mapper makes it easy to map javascript classes to MongoDB documents and back using @decorators.

Install

yarn add type-mongo-mapper

Usage

If you want to take advantage of an upcoming feature in mongodb, you must use mongodb@3.1.0 and higher. Otherwise, you can just use the "map" and "unmap" methods manually when dealing with plain documents. See this commit

Quickstart

import { Document, Field, mapper } from 'type-mongo-mapper';
 
@Document()
class User {
  @Field()
  public _id: ObjectID;
 
  @Field()
  public firstName: string;
 
  @Field()
  public lastName: string;
 
  get id(): string {
    return this._id.toHexString();
  }
}
 
const { map, unmap } = mapper(User);
 
// pass "map" & "umap" options to collection
const usersCollection = db.collection('users', { map, unmap });
 
// Document to User
 
const user = await usersCollection.findOne({ /* ... */ }) // user is an instanceof User
 
// Documents to Users
 
const users = await collection.find({ /* ... */ }); // each item in cursor will be a User
 
 
// Save a User.
 
const user = new User();
user.firstName = 'John';
user.lastName = 'Doe';
 
await collection.insertOne(user);
 

Readme

Keywords

none

Package Sidebar

Install

npm i type-mongo-mapper

Weekly Downloads

1

Version

0.0.6

License

MIT

Unpacked Size

38.2 kB

Total Files

20

Last publish

Collaborators

  • jrdn