jeka-kiselyov / fastify-mongoose-api

Fastify plugin to expose API for Mongoose MongoDB models
https://fastify-mongoose-api-app.herokuapp.com/
MIT License
49 stars 7 forks source link

Thoughts on supporting projections? #1

Closed chill-cod3r closed 3 years ago

chill-cod3r commented 4 years ago

It would be awesome if projections could be defined for certain routes (such as the list route) or if they could be sent in via route query params. Do you have any thoughts on the best way to go about this / any interest in adding it as a feature? I'd be happy to contribute.

Why would it be useful? Mainly for performance reasons. I have some fields that are really large that I would like to have only display on the "find by id" route but not on the "list" route.

EDIT: first pass at "hacking" it in there. I feel like there's probably a better way than putting a "default list projection" on the model but it works:


// in my model

MySchema.set('listProjection', { fieldIDontWant1: 0, otherFieldIDontWant: 0 });

// in APIRouter.js

async getListResponse(query, request, reply) {
    const offset = request.query.offset ? parseInt(request.query.offset, 10) : 0;
    const limit = request.query.limit ? parseInt(request.query.limit, 10) : 100;
    const sort = request.query.sort ? request.query.sort : null;
    const filter = request.query.filter ? request.query.filter : null;
    const search = request.query.search ? request.query.search : null;
    const match = request.query.match ? request.query.match : null;

    const populate = request.query.populate ? request.query.populate : null;

    const projection = this._model.schema.get('listProjection');

    if (projection) {
        query.projection(projection);
    }

  // rest of function as normal, could reorder it however you want
jeka-kiselyov commented 4 years ago

Sorry for a late response, @wolfejw86

Definitely this is must have feature. As a quick fix based on current methods, it's possible to use apiValues method on the model. You can check out https://github.com/jeka-kiselyov/sample-fastify-mongoose-api-app/blob/master/models/user.js ( filtering out password in API responses ) to check it in action. But projection would be much faster, I will add it to methods.

phmz commented 3 years ago

Is this something you are still interested in implementing? If so, I can submit a pull request.

jeka-kiselyov commented 3 years ago

This looks great! @phmz , thank you! I will check tests and do a merge tomorrow.

jeka-kiselyov commented 3 years ago

Works great and nicely covered. Merged and published to npm as 1.1.7

Thanks again @phmz