[go: up one dir, main page]

Skip to content

Tiny utility tool that populates given data's DBRefs with native MongoDB driver

License

Notifications You must be signed in to change notification settings

Lchemist/mongodb-populate-refs

Repository files navigation

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

About

Tiny utility tool that populates given data's DBRefs with native MongoDB driver

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project