replace_one.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict';
  2. const OperationBase = require('./operation').OperationBase;
  3. const updateDocuments = require('./common_functions').updateDocuments;
  4. const hasAtomicOperators = require('../utils').hasAtomicOperators;
  5. class ReplaceOneOperation extends OperationBase {
  6. constructor(collection, filter, replacement, options) {
  7. super(options);
  8. if (hasAtomicOperators(replacement)) {
  9. throw new TypeError('Replacement document must not contain atomic operators');
  10. }
  11. this.collection = collection;
  12. this.filter = filter;
  13. this.replacement = replacement;
  14. }
  15. execute(callback) {
  16. const coll = this.collection;
  17. const filter = this.filter;
  18. const replacement = this.replacement;
  19. const options = this.options;
  20. // Set single document update
  21. options.multi = false;
  22. // Execute update
  23. updateDocuments(coll, filter, replacement, options, (err, r) =>
  24. replaceCallback(err, r, replacement, callback)
  25. );
  26. }
  27. }
  28. function replaceCallback(err, r, doc, callback) {
  29. if (callback == null) return;
  30. if (err && callback) return callback(err);
  31. if (r == null) return callback(null, { result: { ok: 1 } });
  32. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  33. r.upsertedId =
  34. Array.isArray(r.result.upserted) && r.result.upserted.length > 0
  35. ? r.result.upserted[0] // FIXME(major): should be `r.result.upserted[0]._id`
  36. : null;
  37. r.upsertedCount =
  38. Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  39. r.matchedCount =
  40. Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  41. r.ops = [doc]; // TODO: Should we still have this?
  42. if (callback) callback(null, r);
  43. }
  44. module.exports = ReplaceOneOperation;