@topmodel/mongo
v1.0.4
Published
Topmodel Connector for MongoDB
Maintainers
Readme
@topmodel/mongo
Mongo connector (compatible with topmodel models)
Install
With npm
npm install @topmodel/mongoor yarn
yarn add @topmodel/mongoUsage
Setup your mongo connector Plugin and pass it in the model options:
import { Model } from '@topmodel/core'
import { MongoPlugin } from '@topmodel/mongo'
const { MONGO_URL, MONGO_DATABASE } = process.env
const mongo = new MongoPlugin({
url: MONGO_URL,
database: MONGO_DATABASE
})
const options = { db: mongo }
class User extends Model {
constructor(data){
super(data, options)
}
}
// User class is now ready to interact with Mongo !You can then use your User model and persist its data within mongo
// example :
const user = new User({ email: '[email protected]' })
const saved = await user.save()
console.log(saved) // saved user in mongoCollections
Note: by default topmodel core will attribute a table name related to your model name, for example model User will become user table in SQL or collection in Mongo.
If you want to force the collection, please refer to the core model option table here
API
Topmodel db connectors has built-in methods extended to your models :
| Method | Return | Comments |
|----------|:-------------|:------|
| save() | Promise(Model) | create or update if data.id or data._id`` is specified |
| read()| Promise(Model) | will retrieve the data in the database (will requireidor_id) |
| del()| Promise(Model) | will delete the data in the database (will requireidor_id`) |
save
Create or update your model in mongo
// create
const user = new User({ email: '[email protected]' })
const saved = await user.save()
console.log(saved.body)
// { _id: '507f1f77bcf86cd799439011' , email: '[email protected]' }
// or update
const user = new User({ _id: '507f1f77bcf86cd799439011', email: '[email protected]' })
const updated = await user.save()
console.log(updated.body)
// { _id: '507f1f77bcf86cd799439011', email: '[email protected]' }read
Read data from the database and populate the Model
const user = new User({ _id: '507f1f77bcf86cd799439011' })
await user.read()
console.log(user.body)
// { _id: '507f1f77bcf86cd799439011' , email: '[email protected]' }del
Delete data in the database
const user = new User({ _id: '507f1f77bcf86cd799439011' })
const deleted = await user.del()
console.log(deleted) // true 