lookup-pipeline.test.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import * as assert from 'power-assert'
  2. import tcb from '../../../src/index'
  3. import * as Config from '../../config.local'
  4. import * as common from '../../common/index'
  5. const app = tcb.init(Config)
  6. const db = app.database()
  7. const _ = db.command
  8. const $ = db.command.aggregate
  9. describe('projection', () => {
  10. const collName1 = 'test-lookup-pipeline1'
  11. const collName2 = 'test-lookup-pipeline2'
  12. let collection1 = null
  13. let collection2 = null
  14. const data = [
  15. { category: 'Web', tags: ['JavaScript', 'C#'] },
  16. { category: 'Web', tags: ['Go', 'C#'] },
  17. { category: 'Life', tags: ['Go', 'Python', 'JavaScript'] }
  18. ]
  19. beforeAll(async () => {
  20. collection1 = await common.safeCollection(db, collName1)
  21. await collection1.remove()
  22. await collection1.create(data)
  23. collection2 = await common.safeCollection(db, collName2)
  24. await collection2.remove()
  25. await collection2.create(data)
  26. })
  27. afterAll(async () => {
  28. await collection1.remove()
  29. await collection2.remove()
  30. })
  31. it('lookup', async () => {
  32. const result = await db
  33. .collection(collName1)
  34. .aggregate()
  35. .lookup({
  36. from: collName2,
  37. localField: 'category',
  38. foreignField: 'category',
  39. as: 'docs'
  40. })
  41. .end()
  42. assert.strictEqual(result.data[0].docs.length, 2)
  43. })
  44. it('lookup with pipeline', async () => {
  45. const result = await db
  46. .collection(collName1)
  47. .aggregate()
  48. .lookup({
  49. from: collName2,
  50. pipeline: $.pipeline()
  51. .match({
  52. category: 'Web'
  53. })
  54. .done(),
  55. as: 'docs'
  56. })
  57. .end()
  58. assert.strictEqual(result.data[0].docs.length, 2)
  59. assert.strictEqual(result.data[1].docs.length, 2)
  60. assert.strictEqual(result.data[2].docs.length, 2)
  61. })
  62. })