insert_one.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. const MongoError = require('../core').MongoError;
  3. const OperationBase = require('./operation').OperationBase;
  4. const insertDocuments = require('./common_functions').insertDocuments;
  5. class InsertOneOperation extends OperationBase {
  6. constructor(collection, doc, options) {
  7. super(options);
  8. this.collection = collection;
  9. this.doc = doc;
  10. }
  11. execute(callback) {
  12. const coll = this.collection;
  13. const doc = this.doc;
  14. const options = this.options;
  15. if (Array.isArray(doc)) {
  16. return callback(
  17. MongoError.create({ message: 'doc parameter must be an object', driver: true })
  18. );
  19. }
  20. insertDocuments(coll, [doc], options, (err, r) => {
  21. if (callback == null) return;
  22. if (err && callback) return callback(err);
  23. // Workaround for pre 2.6 servers
  24. if (r == null) return callback(null, { result: { ok: 1 } });
  25. // Add values to top level to ensure crud spec compatibility
  26. r.insertedCount = r.result.n;
  27. r.insertedId = doc._id;
  28. if (callback) callback(null, r);
  29. });
  30. }
  31. }
  32. module.exports = InsertOneOperation;