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',
},
]
},
// ...
] |
- 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()
})
- 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()
})
- 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'])