A @decorator based MongoDB document to ES6 class mapper.
type-mongo-mapper makes it easy to map javascript classes to MongoDB documents and back using @decorators.
yarn add type-mongo-mapper
If you want to take advantage of an upcoming feature in mongodb, you must use [email protected]
and higher. Otherwise, you can just
use the "map" and "unmap" methods manually when dealing with plain documents. See this commit
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);