micro-mongoose-models
v0.1.1
Published
Return Mongoose models from zeit/micro microservices
Downloads
2
Readme
micro-mongoose-models
Return Mongoose models right from your zeit/micro microservices.
Models get converted to plain objects with model's .toObject
method.
Usage
Before
const handler = (req, res) => {
const products = await Product.find()
return products.map(p => p.toObject())
}
module.exports = handler
After
const handler = (req, res) =>
Product.find()
module.exports = mongooseModels(handler)
Important: all examples assume Mongoose is configured to use promises.
Details on Mongoose docs.
mongoose.Promise = global.Promise
##Install
npm install --save micro-mongoose-models
# or
yarn add micro-mongoose-models
Examples
Let's assume you have Product
model defined in a following way:
const toObject = {
transform: (doc, res) => {
delete res._id
delete res.__v
res.id = doc.id
},
}
const Product = mongoose.model('Product', mongoose.Schema({
name: String,
price: Number,
}, { toObject }))
With single model
const mongooseModels = require('micro-mongoose-models')
const handler = async(req, res) =>
User.findById(req.params.id)
module.exports = mongooseModels(handler)
With array of models
const handler = async(req, res) =>
User.find()
Combine with any other middleware (better with micro-compose):
const compose = require('micro-compose')
const someMiddleware = require('some-middleware')
const mongooseModels = require('micro-mongoose-models')
const handler = (req, res) =>
User.find()
module.exports = compose(
someMiddleware,
mongooseModels)(handler)