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

@valv/mongodb

v0.1.0

Published

MongoDB adapter for valv

Readme

@valv/mongodb

@valv/mongodb connects Valv to MongoDB through the official Node.js driver. It introspects collections, applies Valv policies, and compiles the shared query grammar into MongoDB aggregation pipelines.

[!NOTE] This is an experimental feature currently under active development.

The adapter is read-only. It supports top-level fields, nested document fields, declared belongsTo and hasMany relations, filters, projection, sorting, pagination, the base aggregate functions, and dateTrunc. Writes are not available.

Install

Install the adapter and the MongoDB driver:

npm install @valv/mongodb mongodb

Connect

Pass a connected MongoDB Db and let Valv introspect its collections:

import { MongoClient } from "mongodb"
import { createValv } from "@valv/mongodb"

const client = new MongoClient(process.env.DATABASE_URL!)
await client.connect()

const valv = await createValv(client.db("analytics"), {
  schema: "introspect",
  defaultPolicy: "deny-all",
})

valv.policy("orders", (ctx) => ({
  read: { tenantId: ctx.tenant.id },
  fields: {
    allow: ["_id", "customerId", "status", "total", "metadata__source", "createdAt"],
  },
}))

MongoDB introspection merges collection $jsonSchema validators with a sample of existing documents. Use field allowlists for collections whose document shape can change. New or unsampled fields remain inaccessible until they enter the catalog and the policy explicitly allows them.

You can also connect from a URL:

import { createValvFromUrl } from "@valv/mongodb"

const { valv, stop } = await createValvFromUrl(process.env.DATABASE_URL!, {
  database: "analytics",
  defaultPolicy: "deny-all",
})

Call stop() when the process no longer needs the connection.

Nested document fields

Embedded objects are flattened into catalog fields with __ between path segments. A document { metadata: { source: "api" } } exposes metadata__source. Intermediate objects are not themselves selectable.

Query the flattened name. Valv compiles it to the dotted BSON path:

await valv.run(
  {
    from: "orders",
    select: { source: { col: "metadata__source" } },
    where: { metadata__source: { startsWith: "api" } },
  },
  ctx,
)

If a physical top-level field uses the same name as a generated nested field, the physical field wins. The nested path stays inaccessible so one policy name cannot refer to two BSON values.

Relations

MongoDB has no foreign-key metadata to introspect, so you declare relations when you create the instance. Pass them to createValv or createValvFromUrl. belongsTo and hasMany are supported. manyToMany is not.

const { valv, stop } = await createValvFromUrl(process.env.DATABASE_URL!, {
  database: "analytics",
  defaultPolicy: "deny-all",
  relations: {
    orders: {
      customer: {
        name: "customer",
        targetResource: "customers",
        type: "belongsTo",
        foreignKey: "customerId",
        targetKey: "_id",
      },
    },
  },
})

For a hand-defined schema, put the same relation objects on each resource instead of passing relations.

A dotted path in the query follows the relation. Valv compiles it to $lookup plus $unwind, then applies the related resource's policy:

valv.policy("orders", (ctx) => ({
  read: { tenantId: ctx.tenant.id },
  fields: { allow: ["_id", "customerId", "status", "total", "createdAt"] },
}))
valv.policy("customers", (ctx) => ({
  read: { tenantId: ctx.tenant.id },
  fields: { allow: ["_id", "name"] },
}))

await valv.run(
  {
    from: "orders",
    select: {
      customer: { col: "customer.name" },
      status: true,
      revenue: { sum: "total" },
    },
    groupBy: ["customer.name", "status"],
  },
  ctx,
)

The lookup is an inner join. A missing related document, or one that fails the joined resource's policy, drops the parent row.

See examples/mongodb for a tenant-scoped query that joins orders to customers, reads metadata.source, and buckets by month.

MongoDB functions

On top of the standard aggregates (count, sum, avg, min, max), this dialect adds dateTrunc:

| Function | Use | |---|---| | dateTrunc(col, unit) | Bucket a date. unit is minute, hour, day, month, or year. |

{
  from: "orders",
  select: {
    month: { dateTrunc: ["createdAt", "month"] },
    revenue: { sum: "total" },
  },
  groupBy: ["month"],
}

License

MIT