collection.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { DocumentReference } from './document';
  2. import { Query } from './query';
  3. import Aggregation from './aggregate';
  4. import { serialize } from './serializer/datatype';
  5. import { getReqOpts, stringifyByEJSON } from './utils/utils';
  6. import { Validate } from './validate';
  7. import { isArray } from './utils/type';
  8. export class CollectionReference extends Query {
  9. constructor(db, coll, apiOptions, transactionId) {
  10. super(db, coll, '', apiOptions, transactionId);
  11. if (transactionId) {
  12. this._transactionId = transactionId;
  13. }
  14. }
  15. get name() {
  16. return this._coll;
  17. }
  18. doc(docID) {
  19. if (typeof docID !== 'string' && typeof docID !== 'number') {
  20. throw new Error('docId必须为字符串或数字');
  21. }
  22. return new DocumentReference(this._db, this._coll, this._apiOptions, docID, this._transactionId);
  23. }
  24. async add(data) {
  25. let transformData = data;
  26. if (!isArray(data)) {
  27. transformData = [data];
  28. }
  29. transformData = transformData.map(item => {
  30. return stringifyByEJSON(serialize(item));
  31. });
  32. let params = {
  33. collectionName: this._coll,
  34. data: transformData
  35. };
  36. if (this._transactionId) {
  37. params.transactionId = this._transactionId;
  38. }
  39. const res = await this._request.send('database.insertDocument', params, getReqOpts(this._apiOptions));
  40. if (res.code) {
  41. return res;
  42. }
  43. if (!isArray(data)) {
  44. if (this._transactionId) {
  45. return {
  46. inserted: 1,
  47. ok: 1,
  48. id: res.data.insertedIds[0],
  49. requestId: res.requestId
  50. };
  51. }
  52. return {
  53. id: res.data.insertedIds[0],
  54. requestId: res.requestId
  55. };
  56. }
  57. return {
  58. ids: res.data.insertedIds,
  59. requestId: res.requestId
  60. };
  61. }
  62. aggregate() {
  63. return new Aggregation(this._db, this._coll);
  64. }
  65. options(apiOptions) {
  66. Validate.isValidOptions(apiOptions);
  67. return new CollectionReference(this._db, this._coll, apiOptions, this._transactionId);
  68. }
  69. }