db_ref.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. /**
  3. * A class representation of the BSON DBRef type.
  4. */
  5. class DBRef {
  6. /**
  7. * Create a DBRef type
  8. *
  9. * @param {string} collection the collection name.
  10. * @param {ObjectId} oid the reference ObjectId.
  11. * @param {string} [db] optional db name, if omitted the reference is local to the current db.
  12. * @return {DBRef}
  13. */
  14. constructor(collection, oid, db, fields) {
  15. // check if namespace has been provided
  16. const parts = collection.split('.');
  17. if (parts.length === 2) {
  18. db = parts.shift();
  19. collection = parts.shift();
  20. }
  21. this.collection = collection;
  22. this.oid = oid;
  23. this.db = db;
  24. this.fields = fields || {};
  25. }
  26. /**
  27. * @ignore
  28. * @api private
  29. */
  30. toJSON() {
  31. const o = Object.assign(
  32. {
  33. $ref: this.collection,
  34. $id: this.oid
  35. },
  36. this.fields
  37. );
  38. if (this.db != null) o.$db = this.db;
  39. return o;
  40. }
  41. /**
  42. * @ignore
  43. */
  44. toExtendedJSON() {
  45. let o = {
  46. $ref: this.collection,
  47. $id: this.oid
  48. };
  49. if (this.db) o.$db = this.db;
  50. o = Object.assign(o, this.fields);
  51. return o;
  52. }
  53. /**
  54. * @ignore
  55. */
  56. static fromExtendedJSON(doc) {
  57. var copy = Object.assign({}, doc);
  58. ['$ref', '$id', '$db'].forEach(k => delete copy[k]);
  59. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  60. }
  61. }
  62. Object.defineProperty(DBRef.prototype, '_bsontype', { value: 'DBRef' });
  63. module.exports = DBRef;