update_many.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. const OperationBase = require('./operation').OperationBase;
  3. const updateDocuments = require('./common_functions').updateDocuments;
  4. const hasAtomicOperators = require('../utils').hasAtomicOperators;
  5. const Aspect = require('./operation').Aspect;
  6. const defineAspects = require('./operation').defineAspects;
  7. class UpdateManyOperation extends OperationBase {
  8. constructor(collection, filter, update, options) {
  9. super(options);
  10. if (!hasAtomicOperators(update)) {
  11. throw new TypeError('Update document requires atomic operators');
  12. }
  13. this.collection = collection;
  14. this.filter = filter;
  15. this.update = update;
  16. }
  17. execute(callback) {
  18. const coll = this.collection;
  19. const filter = this.filter;
  20. const update = this.update;
  21. const options = this.options;
  22. // Set single document update
  23. options.multi = true;
  24. // Execute update
  25. updateDocuments(coll, filter, update, options, (err, r) => {
  26. if (callback == null) return;
  27. if (err) return callback(err);
  28. if (r == null) return callback(null, { result: { ok: 1 } });
  29. // If an explain operation was executed, don't process the server results
  30. if (this.explain) return callback(undefined, r.result);
  31. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  32. r.upsertedId =
  33. Array.isArray(r.result.upserted) && r.result.upserted.length > 0
  34. ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id`
  35. : null;
  36. r.upsertedCount =
  37. Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  38. r.matchedCount =
  39. Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  40. callback(null, r);
  41. });
  42. }
  43. }
  44. defineAspects(UpdateManyOperation, [Aspect.EXPLAINABLE]);
  45. module.exports = UpdateManyOperation;