npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@querykitjs/mongoose

v2.0.0

Published

Advanced filtering + flexible pagination repository layer for Mongoose (MongoDB).

Readme

English · O'zbekcha

@querykitjs/mongoose

npm license

Mongoose (MongoDB) uchun ilg'or filtrlash + moslashuvchan paginatsiya repository qatlami.

Mongoose ustiga qo'lda yozadigan kodni — murakkab filterlar, 3 xil paginatsiya, tranzaksiya, RBAC scope, soft-delete, bulk/aggregatsiya — bitta tipli repository'ga jamlaydi. Natija tiplari with/columnsdan avtomatik chiqariladi. Ommaviy yuza @querykitjs/drizzle-pg bilan bir xil — shuning uchun bitta frontend kontrakti (@querykitjs/web) ham Postgres, ham MongoDB backend'ini boshqaradi.

Tez boshlash

import mongoose, { Schema } from "mongoose";
import { createRegistry, createFilters } from "@querykitjs/mongoose";

// 1. oddiy Mongoose modeli
interface IUser {
  _id: mongoose.Types.ObjectId;
  name: string;
  email: string;
  age: number | null;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}
const User = mongoose.model<IUser>("User", new Schema<IUser>({ name: String, email: String, age: Number, status: String }, { timestamps: true }));

// 2. ulaning, so'ng connection'dan registry quring
await mongoose.connect(process.env.MONGO_URL!);
export const registry = createRegistry(mongoose.connection);

// 3. har model uchun bitta tipli repository
export const usersRepository = registry.repository(User);

// 4. so'rov — filter, sort, pagination, hammasi tipli
const f = createFilters<IUser>();
const { data, meta } = await usersRepository.findList({
  page: 2,
  perPage: 20,
  filter: f.and(f.eq("status", "active"), f.gte("age", 18)),
  sort: [{ key: "createdAt", direction: "desc" }],
});
//    ^? data: IUser[]   meta: { total_items, total_pages, has_next, ... }

Imkoniyatlar

  • Ilg'or filterlar — ichma-ich and/or/not, 25+ operator, raw Mongo query escape-hatch, f helperlar. SQL uch-qiymatli mantiq pariteti (negatsiya null/yo'qni chetlaydi).
  • 3 xil paginatsiya — offset (findList), infinite scroll (findInfinite), cursor/keyset (findCursor, default kalit _id).
  • with + columns inference — populate qilingan relation'lar va tanlangan maydonlar qo'lda generic'siz tiplanadi.
  • Ko'p-maydonli sort, count, exists, aggregate (count/sum/avg/min/max + groupBy).
  • Tranzaksiya — registry.transaction(); ichidagi repository'lar avtomatik qo'shiladi (replica set talab qiladi).
  • Scoped repository — RBAC / multi-tenancy uchun doimiy asosiy filter + create default'lari.
  • Soft-delete — deletedAt path bo'lsa avtomatik; softDelete/restore/withDeleted.
  • Upsert / bulk — upsert, upsertMany (avto-chunk, input-tartibda natija).
  • id ↔ _id alias — wire kontrakti adapterlar bo'ylab bir xil; o'qishlar oddiy POJO qaytaradi (.lean()).

O'rnatish

bun add @querykitjs/mongoose mongoose
# yoki: npm i @querykitjs/mongoose mongoose

mongoose (>= 8) — peer dependency.

Sozlash

1. Registry (bir marta)

// db/registry.ts
import mongoose from "mongoose";
import { createRegistry } from "@querykitjs/mongoose";

export const registry = createRegistry(mongoose.connection);
// yoki paginatsiya default'larини sozlash:
// export const registry = createRegistry(mongoose.connection, { defaultPerPage: 20, defaultLimit: 20 });

connection tashqaridan beriladi (tranzaksiya to'g'ri session'ni ulashsin uchun).

createRegistry opsiyalari — drizzle-pg adapteri bilan aynan bir xil:

| Opsiya | Default | Ma'nosi | | -------------------- | --------------------------------- | --------------------------------------------------------- | | defaultPerPage | core DEFAULT_PER_PAGE (20) | findList sahifa o'lchami | | defaultLimit | core DEFAULT_LIMIT (20) | findInfinite/findCursor limiti | | maxPerPage | core DEFAULT_MAX_PER_PAGE (200) | perPage yuqori chegarasi (Infinity — o'chirish) | | maxLimit | core DEFAULT_MAX_LIMIT (200) | limit yuqori chegarasi | | strict | false | noma'lum kalit → QueryKitError (400), jimgina skip emas | | onSkippedCondition | — | tashlab yuborilgan har bir shart uchun callback |

maxPerPage/maxLimit — ikkinchi himoya qatlami: validatsiya (@querykitjs/zod factory'lari) chetlab o'tilsa ham repository o'zi clamp qiladi.

2. Har model uchun repository

// db/repositories/users.repository.ts
import { registry } from "../registry";
import { User } from "../models/user.model";

export const usersRepository = registry.repository(User, base => ({
  findByEmail: (email: string) => base.findOne({ filter: [{ key: "email", operation: "=", value: email }] }),
}));

repository() to'rt shaklda chaqiriladi (drizzle-pg adapteri bilan bir xil):

registry.repository(User);                            // sof
registry.repository(User, base => ({ … }));           // + custom metodlar
registry.repository(User, options);                   // + per-repo opsiyalar
registry.repository(User, options, base => ({ … }));  // ikkisi ham

3. Projection himoyasi (RepositoryOptions)

columns clientdan kelishi mumkin, shuning uchun xavfsiz tanlov repository'da belgilanadi — scope (RBAC) allaqachon shu yo'lda:

export const usersRepository = registry.repository(User, {
  forcedColumns: { _id: true, fullName: true, email: true }, // parol hech qachon chiqmaydi
});

// yoki yumshoqroq: client faqat shu ro'yxatdan tanlaydi
export const postsRepository = registry.repository(Post, {
  allowedColumns: ["_id", "title", "createdAt"],
});

| Opsiya | Xulqi | | ---------------- | ------------------------------------------------------------------------------------- | | forcedColumns | client columnsi butunlay e'tiborsiz | | allowedColumns | client tanlovi allowlist bilan kesiladi; kesishma bo'sh bo'lsa → allowlist | | scope | har bir o'qish/yozishga doimiy tenglik filtri (scoped() bilan ham berilishi mumkin) | | relations | populate qilinadigan relation'lar (faqat tip — with inference uchun) |

Muhim nozikliklar:

  • Kesishma bo'sh bo'lganda natija to'liq hujjat emas — allowlistning o'zi.
  • aggregate ham shu guard ostida: min("password") yoki groupBy: "password" projection bilan bir xil miqdorda ma'lumot chiqaradi.
  • cursorKey clientdan keladi va cursor maydoni paginatsiya uchun majburan tanlanadi — guard bor bo'lsa u maydon so'rovda qoladi, lekin qaytariladigan hujjatlardan olib tashlanadi.
  • forcedColumns: {} yoki allowedColumns: [] — repository yaratilishida xato.
  • ⚠️ Guard faqat o'qish metodlariga ta'sir qiladi (findAll/findOne/ findById/findList/findInfinite/findCursor + aggregate). Yozish metodlari (create, upsert, updateById, softDelete, …) tip kontrakti bo'yicha to'liq hujjatni qaytaradi. Yozish natijasini clientga qaytarishdan oldin findById bilan qayta o'qing yoki o'zingiz map qiling.

4. Noto'g'ri shartlar: kuzatish yoki rad etish

Noma'lum filter/sort kaliti default'da jimgina tashlab yuboriladi. Muammosi: filter natijani cheklash uchun ishlatiladi, shuning uchun typo qilingan kalit yo'qolsa endpoint kutilganidan ko'proq data qaytaradi.

// 1-qadam: kuzatish (xulq o'zgarmaydi)
createRegistry(mongoose.connection, {
  onSkippedCondition: info => logger.warn({ querykit: info }, "shart tashlab yuborildi"),
});

// 2-qadam: log tozalanganda — qattiq rejim
createRegistry(mongoose.connection, { strict: true });
import { QueryKitError } from "@querykitjs/core";

try {
  return await usersRepository.findList(params);
} catch (err) {
  if (err instanceof QueryKitError) return c.json({ error: err.message, info: err.info }, 400);
  throw err;
}

scope va cursorKey kaliti har doim fatal (strictdan qat'i nazar).

MongoDB-ga xos jihatlar

  • id ↔ _id. Istalgan joyda "id" ishlating (filter, columns, idKey, cursorKey) — u Mongo'ning _idsiga o'giriladi, wire kontrakti SQL adapter bilan bir xil. Frontend'дан kelган string id'lar avtomatik ObjectIdga cast bo'ladi:
    await usersRepository.findById("665f0e...b3a"); // string → ObjectId
    await usersRepository.findAll({ filter: [{ key: "id", operation: "in", value: [id1, id2] }] });
  • Qiymat cast. Wire string'lar schema tomonidan cast qilinadi — ISO sana → Date, hex string → ObjectId — find, aggregate $match va cursor tokenlarда birxil.
  • O'qishlar .lean() — oddiy POJO (hydrate qilinган Mongoose hujjati emas), SQL adapter qatorlari bilan mos.
  • Cursor default _id bo'yicha (cursorKey bilan o'zgartiring) — insert'larда barqaror.
  • Tranzaksiya replica set talab qiladi — lokal dev uchun bir-nodали yetarli (mongod --replSet rs0 so'ng rs.initiate(), yoki testда mongodb-memory-server).

Ilg'or filterlar

Filter — maydon shartlari va mantiqiy guruhlar (and/or/not) daraxti. Yassi massiv = implicit AND. id — _idga o'giriladi.

import { createFilters } from "@querykitjs/mongoose";
const f = createFilters<IUser>(); // maydon nomi autocomplete

await usersRepository.findAll({
  filter: f.and(f.eq("status", "active"), f.or(f.gte("age", 18), f.in("role", ["admin", "owner"])), f.not(f.isNull("deletedAt"))),
});

Operatorlar: = != > >= < <= (va eq ne gt gte lt lte), like ilike notLike, contains startsWith endsWith (case-insensitive), in notIn, between notBetween (value: [min, max]), isNull isNotNull. Istalgan joyga raw Mongo query obyekti tashlanadi. Qiymatlar o'zgartirilmasdan o'tadi; wire string'lar (sana / ObjectId) schema tomonidan cast qilinadi. Negatsiya operatorlari (ne/notIn/notLike/notBetween va bir-maydonли not) SQL uch-qiymatli mantiqiga mos ravishda null/yo'qni chetlaydi.

Ko'p-maydonli sort

sort: [
  { key: "name", direction: "asc" },
  { key: "createdAt", direction: "desc" },
]; // { name: 1, createdAt: -1 }

Sort — { key, direction }[] massivi, @querykitjs/web va barcha adapterlar bilan bir xil shakl.

Sort berilmasa createdAt DESC ga, u bo'lmasa _id DESC ga tushadi — pagination barqaror bo'lishi uchun deterministik tartib.

Paginatsiya — 3 strategiya

// 1. Offset — total_items / total_pages
const page = await usersRepository.findList({ page: 2, perPage: 20, filter, sort });

// 2. Infinite scroll (limit + offset) — has_more / next_offset
const feed = await usersRepository.findInfinite({ limit: 20, offset: 40 });

// 3. Cursor / keyset (insert'larда barqaror, default `_id` bo'yicha) — next_cursor / prev_cursor
const p1 = await usersRepository.findCursor({ limit: 20, order: "asc" });
const p2 = await usersRepository.findCursor({ limit: 20, cursor: p1.meta.next_cursor });
const back = await usersRepository.findCursor({ cursor: p2.meta.prev_cursor, direction: "backward" });

Tipli relation'lar va maydon tanlash

O'qish metodlari natija tipini with (populate) va columnsdan chiqaradi — qo'lda generic yo'q:

const post = await postsRepository.findById(id, { with: { author: true } });
post?.author.name; // populate qilingan

const rows = await usersRepository.findAll({ columns: { id: true, name: true } });
rows[0].id; // ObjectId
rows[0].email; // ❌ tip xatosi — tanlanmagan

Populate qilingan relation'larni runtime'да tiplash uchun ref model'larni bering: registry.repository(Post, { relations: { author: User } }).

Tranzaksiya

await registry.transaction(async () => {
  await dispatchesRepository.create({ ... });
  await stockRepository.updateById(stockId, { qty: next });
}); // throw -> to'liq rollback

Ichida ishlatilgan repository'lar avtomatik tranzaksiya session'ini oladi (ambient context). MongoDB tranzaksiyasi replica set talab qiladi (lokal dev uchun bir-nodали replica set kifoya). Ichma-ich chaqiruv tashqi session'ni qayta ishlatadi.

Scoped repository (RBAC / multi-tenancy)

const mine = roadmapsRepository.scoped({ supervisorId: user.id });
await mine.findList({ page: 1 }); // { supervisorId: user.id, ... }
await mine.create({ ... });        // supervisorId majburan user.id

Scope'ni registry.repository(Model, { scope }) bilan ham berish mumkin. Noma'lum scope kaliti — repository yaratilishida xato (jimgina tashlansa RBAC filtri yo'qolib ketardi).

Wire (JSON) qiymatlari va DbService'dan migratsiya

Backend so'rov body'sini JSON'da oladi, ya'ni sana har doim string bo'lib keladi. Adapter uni schema path tipiga qarab avtomatik cast qiladi:

{ "key": "createdAt", "operation": "<=", "value": "2026-07-28T12:00:00.000Z" }
  • Date path'lari → ISO string avtomatik Datega aylanadi. Qamrov ataylab drizzle-pg bilan bir xil: u ham faqat JS orqali map qilinadigan tiplarni hukm qiladi, qolganini bazaga qoldiradi.
  • in/notIn massivlari, between/notBetween tuple'lari va cursor token ham qamraladi (cursorKey: "createdAt" ishlaydi).
  • ⚠️ Hujjatlashtirilgan farq: Mongo Date path'da $regex qila olmaydi (Can't use $options with Date), shuning uchun date maydonidagi text-pattern operatori (contains/ilike/…) tashlab yuboriladi. drizzle-pg esa buni bajaradi (Postgres timestamp'ni text sifatida render qiladi). Ikkalasi ham crash qilmaydi; farq onSkippedConditionda ko'rinadi.
  • Parse bo'lmaydigan qiymat ("not-a-date") shartni bekor qiladi (strictda — 400). in ro'yxatidagi bitta yaroqsiz element butun shartni bekor qiladi.

DbService migratsiyasi: eski wire'dagi type: "date" maydoni endi keraksiz — @querykitjs/zod uni strip qiladi (xato bermaydi), coercion esa server tomonda path tipidan avtomatik.

Soft-delete

Schema'да deletedAt path bo'lsa avtomatik yoqiladi. O'qishlar default'да soft-delete qilingan hujjatlarni chiqarib tashlaydi; withDeleted: true ularni ham qo'shadi. { timestamps: true } bo'lmasa lekin qo'lда updatedAt path bo'lsa, har update'да bumps qilinadi.

await postsRepository.softDelete(id);
await postsRepository.restore(id);
await postsRepository.findAll({ withDeleted: true });

Upsert, bulk & aggregatsiya

await usersRepository.upsert({ email: "[email protected]", name: "Ali" }, { target: "email" });
await productsRepository.upsertMany(rows, { target: "externalId" }); // chunk, input tartibda qaytadi
await visitsRepository.aggregate({ count: true, groupBy: "supervisorId" });
await ordersRepository.aggregate({ sum: "amount", groupBy: "region" });

API ma'lumotnoma

| Metod | Qaytaradi | | -------------------------------------------------------------- | ---------------------------- | | findAll(params?) | Row[] | | findOne(params?) / findById(id, params?) | Row \| undefined | | findList(params?) | { data, meta } offset | | findInfinite(params?) | { data, meta } infinite | | findCursor(params?) | { data, meta } cursor | | count(filter?) / exists(filter?) | number / boolean | | aggregate(spec) | AggregateRow[] | | create(values) / createMany(values) | Row / Row[] | | upsert(values, opts) / upsertMany(values, opts) | Row / Row[] | | updateById(id, patch, idKey?) / updateWhere(filter, patch) | Row \| undefined / Row[] | | deleteById(id, idKey?) / deleteWhere(filter) | Row \| undefined / Row[] | | softDelete(id) / restore(id) | Row \| undefined | | scoped(scope) | scoped Repository | | registry.transaction(fn) | fn natijasi |

Ishlab chiqish

bun install
bun run typecheck
bun run lint
bun run build       # tsup -> dist (ESM + CJS + .d.ts)
bun run --filter @querykitjs/mongoose test:smoke   # in-memory replica set (mongodb-memory-server)

Litsenziya

MIT © Suhrobbek Soatov