API Query Parameters to MongoDB

6.1.0 · active · verified Tue Apr 21

api-query-params is a JavaScript library designed to convert standard API URL query parameters into MongoDB query objects, facilitating advanced filtering, sorting, and projection directly from HTTP requests. Currently at version 6.1.0, the package sees active maintenance with minor versions and patches released regularly to address bug fixes and introduce new features. Key differentiators include its comprehensive support for most MongoDB operators ($in, $regexp, $gt, etc.), nested object querying, and type casting, while remaining agnostic to the specific web framework (e.g., Express, Koa) or MongoDB library (e.g., Mongoose). It offers customization for query keys and options and is noted for its compact, dependency-free ES6 codebase, aiming for simplicity and full test coverage.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates integrating `api-query-params` with Express and Mongoose to build a dynamic API endpoint, parsing request query parameters into MongoDB-compatible queries for filtering, sorting, pagination, and projection.

import express from 'express';
import aqp from 'api-query-params';
import mongoose from 'mongoose';

const app = express();

// Dummy Mongoose Setup (replace with your actual connection and model)
mongoose.connect(process.env.MONGODB_URI ?? 'mongodb://localhost:27017/testdb');

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number,
  status: String,
  createdAt: Date
});
const User = mongoose.model('User', UserSchema);

app.get('/users', async (req, res, next) => {
  try {
    const { filter, skip, limit, sort, projection, population } = aqp(req.query);

    // Populate with a dummy 'logs' model if needed for example
    // In a real app, ensure 'population' paths correspond to actual schemas.
    const users = await User.find(filter)
      .skip(skip)
      .limit(limit)
      .sort(sort)
      .select(projection)
      .populate(population)
      .exec();

    res.json(users);
  } catch (err) {
    next(err);
  }
});

app.listen(3000, () => console.log('Server running on port 3000'));

view raw JSON →