NodeJS: How to get the native mongodb client from a jugglingdb adapter


Use in event connected

Example:

import { Schema } from 'jugglingdb'

var schema = new Schema('mongodb',{host:'127.0.0.1',port:27017,database:'demo'})

schema.on('connected', function() {
    // work with database
    let db = this.client
    let collectionUser = db.collection('User')
    console.log(collectionUser)
})

Result:

Collection {
  s: {
    pkFactory: <ref *1> [Function: ObjectID] {
      index: 999321,
      createPk: [Function: createPk],
      createFromTime: [Function: createFromTime],
      createFromHexString: [Function: createFromHexString],
      isValid: [Function: isValid],
      ObjectID: [Circular *1],
      ObjectId: [Circular *1]
    },
    db: Db {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter],
      [Symbol(kCapture)]: false
    },
    topology: Server {
      _events: [Object: null prototype],
      _eventsCount: 8,
      _maxListeners: undefined,
      clientInfo: [Object],
      s: [Object],
      [Symbol(kCapture)]: false
    },
    dbName: 'demo',
    options: { promiseLibrary: [Function], readConcern: undefined },
    namespace: 'demo.User',
    readPreference: null,
    slaveOk: false,
    serializeFunctions: undefined,
    raw: undefined,
    promoteLongs: undefined,
    promoteValues: undefined,
    promoteBuffers: undefined,
    internalHint: null,
    collectionHint: null,
    name: 'User',
    promiseLibrary: [Function: Promise] {
      resolve: [Function: resolve],
      reject: [Function: reject],
      never: [Function: never],
      _defer: [Function: defer],
      _handler: [Function: getHandler],
      all: [Function: all],
      race: [Function: race],
      _traverse: [Function: traverse],
      _visitRemaining: [Function: visitRemaining],
      onFatalRejection: [Function (anonymous)],
      onPotentiallyUnhandledRejectionHandled: [Function (anonymous)],
      onPotentiallyUnhandledRejection: [Function (anonymous)],
      exitContext: [Function: noop],
      enterContext: [Function: noop],
      createContext: [Function: noop],
      any: [Function: any],
      some: [Function: some],
      settle: [Function: settle],
      map: [Function: map],
      filter: [Function: filter],
      reduce: [Function: reduce],
      reduceRight: [Function: reduceRight],
      iterate: [Function: iterate],
      unfold: [Function: unfold]
    },
    readConcern: undefined
  }
}

You can use a variable to store client Object:

import { Schema } from 'jugglingdb'
 
var schema = new Schema('mongodb',{host:'127.0.0.1',port:27017,database:'demo'}), db

schema.on('connected', function() {
    // work with database    
    db = this.client
})

Leave a Reply