replace_one.js 1.5 KB

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