write_command.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. 'use strict';
  2. const MongoError = require('../error').MongoError;
  3. const collectionNamespace = require('./shared').collectionNamespace;
  4. const command = require('./command');
  5. function writeCommand(server, type, opsField, ns, ops, options, callback) {
  6. if (ops.length === 0) throw new MongoError(`${type} must contain at least one document`);
  7. if (typeof options === 'function') {
  8. callback = options;
  9. options = {};
  10. }
  11. options = options || {};
  12. const ordered = typeof options.ordered === 'boolean' ? options.ordered : true;
  13. const writeConcern = options.writeConcern;
  14. const writeCommand = {};
  15. writeCommand[type] = collectionNamespace(ns);
  16. writeCommand[opsField] = ops;
  17. writeCommand.ordered = ordered;
  18. if (writeConcern && Object.keys(writeConcern).length > 0) {
  19. writeCommand.writeConcern = writeConcern;
  20. }
  21. if (options.collation) {
  22. for (let i = 0; i < writeCommand[opsField].length; i++) {
  23. if (!writeCommand[opsField][i].collation) {
  24. writeCommand[opsField][i].collation = options.collation;
  25. }
  26. }
  27. }
  28. if (options.bypassDocumentValidation === true) {
  29. writeCommand.bypassDocumentValidation = options.bypassDocumentValidation;
  30. }
  31. const commandOptions = Object.assign(
  32. {
  33. checkKeys: type === 'insert',
  34. numberToReturn: 1
  35. },
  36. options
  37. );
  38. command(server, ns, writeCommand, commandOptions, callback);
  39. }
  40. module.exports = writeCommand;