mongodb-populate-refs
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

mongodb-populate-refs

build Coverage Status NPM semantic-release Commitizen friendly Conventional Changelog

Tiny utility tool that populates embedded DBRefs with native MongoDB driver.

Before After
[
  {
    _id: 'book1',
    author: {
      $ref: 'user-collection',
      $id: 'uid1'
    },
    vendors: [
      {
        $ref: 'vendor-collection',
        $id: 'vid1'
      },
      {
        $ref: 'vendor-collection',
        $id: 'vid2',
        $db: 'another-db'
      },
    ]
  },
  // ...
]
[
  {
    _id: 'book1',
    author: {
      _id: 'uid1'
      name: 'John Doe',
      age: 33,
    },
    vendors: [
      { 
        _id: 'vid1'
        name: 'BookMart',
      },
      {
        _id: 'vid2'
        name: 'Barnes & Nobel',
      },
    ]
  },
  // ...
]

Usage

  1. If all DBRefs are pointing to documents in the same database:
import client from 'WHERE_MONGODB_CLIENT_IS_EXPORTED'
import { fromDb } from 'mongodb-populate-refs'
// OR: import { populateFromDb } from 'mongodb-populate-refs'

client.connect(async () => {
  const db = client.db('DB_NAME')
  const rawData = await db.collection('COLLECTION_NAME').find().toArray()

  const populatedData = await fromDb(db).populate(rawData)
  // OR: await populateFromDb(db, rawData)

  client.close()
})
  1. If DBRefs are pointing to documents in multiple databases:
import client from 'WHERE_MONGODB_CLIENT_IS_EXPORTED'
import populate from 'mongodb-populate-refs'
// OR: import { fromClient } from 'mongodb-populate-refs'

client.connect(async () => {
  const defaultDb = 'DB_NAME'
  const rawData = await client.db(defaultDb).collection('COLLECTION_NAME').find().toArray()
  const populatedData = await populate(client, defaultDb, rawData)
  // OR: await fromClient(client).defaultDb(defaultDb).populate(rawData)

  client.close()
})
  1. To limit the returned populated fields:
// In the examples below, only '_id', 'name', 'createdAt' fields will be read from the referenced documents.
await fromDb(db).populate(rawData, ['_id', 'name', 'createdAt'])
await populateFromDb(db, rawData, ['_id', 'name', 'createdAt'])
await populate(client, 'DEFAULT_DB', rawData, ['_id', 'name', 'createdAt'])
await fromClient(client).defaultDb('DEFAULT_DB').populate(rawData, ['_id', 'name', 'createdAt'])

License

Apache License 2.0

Readme

Keywords

Package Sidebar

Install

npm i mongodb-populate-refs

Weekly Downloads

0

Version

1.0.0

License

Apache-2.0

Unpacked Size

32.6 kB

Total Files

6

Last publish

Collaborators

  • lchemist