create_collection.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. 'use strict';
  2. const Aspect = require('./operation').Aspect;
  3. const defineAspects = require('./operation').defineAspects;
  4. const CommandOperation = require('./command');
  5. const applyWriteConcern = require('../utils').applyWriteConcern;
  6. const loadCollection = require('../dynamic_loaders').loadCollection;
  7. const MongoError = require('../core').MongoError;
  8. const ReadPreference = require('../core').ReadPreference;
  9. const ILLEGAL_COMMAND_FIELDS = new Set([
  10. 'w',
  11. 'wtimeout',
  12. 'j',
  13. 'fsync',
  14. 'autoIndexId',
  15. 'strict',
  16. 'serializeFunctions',
  17. 'pkFactory',
  18. 'raw',
  19. 'readPreference',
  20. 'session',
  21. 'readConcern',
  22. 'writeConcern'
  23. ]);
  24. class CreateCollectionOperation extends CommandOperation {
  25. constructor(db, name, options) {
  26. super(db, options);
  27. this.name = name;
  28. }
  29. _buildCommand() {
  30. const name = this.name;
  31. const options = this.options;
  32. const cmd = { create: name };
  33. for (let n in options) {
  34. if (
  35. options[n] != null &&
  36. typeof options[n] !== 'function' &&
  37. !ILLEGAL_COMMAND_FIELDS.has(n)
  38. ) {
  39. cmd[n] = options[n];
  40. }
  41. }
  42. return cmd;
  43. }
  44. execute(callback) {
  45. const db = this.db;
  46. const name = this.name;
  47. const options = this.options;
  48. const Collection = loadCollection();
  49. let listCollectionOptions = Object.assign({ nameOnly: true, strict: false }, options);
  50. listCollectionOptions = applyWriteConcern(listCollectionOptions, { db }, listCollectionOptions);
  51. function done(err) {
  52. if (err) {
  53. return callback(err);
  54. }
  55. try {
  56. callback(
  57. null,
  58. new Collection(db, db.s.topology, db.databaseName, name, db.s.pkFactory, options)
  59. );
  60. } catch (err) {
  61. callback(err);
  62. }
  63. }
  64. const strictMode = listCollectionOptions.strict;
  65. if (strictMode) {
  66. db.listCollections({ name }, listCollectionOptions)
  67. .setReadPreference(ReadPreference.PRIMARY)
  68. .toArray((err, collections) => {
  69. if (err) {
  70. return callback(err);
  71. }
  72. if (collections.length > 0) {
  73. return callback(
  74. new MongoError(`Collection ${name} already exists. Currently in strict mode.`)
  75. );
  76. }
  77. super.execute(done);
  78. });
  79. return;
  80. }
  81. // otherwise just execute the command
  82. super.execute(done);
  83. }
  84. }
  85. defineAspects(CreateCollectionOperation, Aspect.WRITE_OPERATION);
  86. module.exports = CreateCollectionOperation;