yggio-populate-request
v0.0.5
Published
pre-populate req object using {'propName', 'modelName'}
Downloads
4
Readme
yggio-populate-request: the public parts
yggio-populate-request creates middleware that populates an express http request with specified database documents.
Usage
Initialize (note that mongoose is injected as an argument)
const app = require('express')(); // yeah, we need an express app..
const mongoose = require('mongoose');
const populator = require('yggio-populate-request');
Given a mongoose model named 'Hoogie', the following creates populator middleware that populates hoogies on the request object:
const populate = populator.populate(mongoose, 'hoogieId', 'Hoogie', 'populated.hoogie');
app.use(populate);
Alternatively you can use an object:
app.use(populator.populate(mongoose, {
idPath: 'hoogieId',
modelName: 'Hoogie',
resultPath: 'populated.hoogie'
}));
The middleware in this case checks for existence of req.body.hoogieId, req.query.hoogieId, and req.params.hoogieId. If an id is found, we try to retrieve the document from mongodb. If the document is found, the hoogie object is placed at 'req.populated.hoogie'.
Note that no validation is ever done.
Also note that if e.g. 'hoogieId' is meant to be found in 'params', 'populate' must be called AFTER the route path has been resolved (and thus a match for the 'hoogieId' parameter found), e.g.:
app.use('/:hoogieId', populate);
Calling the resulting populate middleware multiple times is supported. If an object is found at the object destination (i.e. req.populated.hoogie) the evaluation is aborted.
All errors get swallowed by design. The default behavior is effectively that the populated object is null.
If you want to configure the population of multiple types of models at once (however, this functionality might be altered to objects instead of arrays):
const models = [
['hoogieId', 'Hoogie', 'populated.hoogie'],
['whatsitId', 'Whatsit', 'populated.whatsit']
];
const multiPop = populator.multiPopulate(mongoose, models);
app.use(multiPop);
Alternatively you can use objects:
app.use(populator.multiPopulate(mongoose, [
{
idPath: 'hoogieId',
modelName: 'Hoogie',
resultPath: 'populated.hoogie'
},
{
idPath: 'whatsitId',
modelName: 'Whatsit',
resultPath: 'populated.whatsit'
}
]));
License
yggio-populate-request is under the MIT license. See LICENSE file.