Tool-Kid / express-query-adapter

:mag_right: :dizzy: Transfrom automatically Express.js req.query into your favourite query tool
MIT License
72 stars 29 forks source link

Mongoose adapter #7

Open rgolea opened 5 years ago

rgolea commented 5 years ago

Hi there!

I love all the stuff this project has and I would like to congratulate you on it and to tell you to keep up the good work!

I would also love the api you got here going to be available to use with mongoose/mongo. The expected behaviour should be absolutely the same one but translated to mongo queries:

foo/?name__contains=foo&role__in=admin,common&age__gte=18&page=3&limit=10

should translate to mongo like the following:

{
    name: {
           $regex: /foo/gi
    },
    role: {
          $in: ['admin', 'common']
    },
    age: {
         $gte: 18
    },
    $skip: 20,
    $limit: 10
}

Then use it in your express like the following

 app.get('/foo', (req, res) => {
  const queryBuilder = new QueryBuilder(req.query); // => Parsed into req.query
  const built = queryBuilder.build();
})

And also use it with Nest like the following:

import { createParamDecorator } from '@nestjs/common';
//should rename this
import { QueryBuilder } from 'express-query-builder';

export const MongooseQuery = createParamDecorator(_$, req => {
    //pass into the constructor the driver to use: 'typeorm', 'mongoose'
    return new QueryBuilder(req.query, 'mongoose').build();
});

And into the controller like the following:

import { Controller, Get } from '@nestjs/common';
import { CAT_MODEL, Cat } from "./users.schema";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";

@Controller('cats')
export class CatsController {
    constructor(
        @InjectModel(CAT_MODEL) private readonly catModel: Model<Cat>
    ){}

    @Get()
    async getCats(@MongooseQuery() query: any):Promise<Cat[]>{
         //maybe... not sure about this part
          return await this.catModel.collection.aggregate([query]);
    }
}

Not sure how aggregate works with mongoose and maybe how to pass in a raw query. Let me know if I can help you with it.

Thanks a lot!

rjlopezdev commented 5 years ago

Hi @rgolea thanks for your interest!

Good feature! But for now is out of scope. I started this project to solve the problem for TypeORM. Nevertheless, I'm interested to that point. The problem is that it requires a big refactor & rethink.

Sharing my thoughts & Roadmap:

In the following weeks, I'll be working alone to stabilize & improve quality of codebase. When it be ready, I will notice you to contribute on mongoose adapter 😃

rjlopezdev commented 1 year ago

Hi @rgolea v2.0.0 release is planning for next month. Now, library is decoupled from TypeORM and it will easily add new adapters. If you are interested, feel free to open a PR :)