Saves the Document to the database if it is valid.
        Returns errors otherwise.
322791
def insert(self, **kwargs):
        
        if self.is_valid:
            before = self.before_insert()
            if before:
                return before

            try:
                self._document['_id'] = self.insert_one(self._document)

                self.after_insert()

                return self._document
            except PyMongoException as exc:
                return PyMongoError(
                    error_message=exc.details.get(
                        'errmsg', exc.details.get('err', 'PyMongoError.')
                    ),
                    operation='insert', collection=type(self).__name__,
                    document=self._document,
                )

        return self._errors
1199864
def save(options={:validate => true})
      context = self.new_record? ? :create : :update
      return false if options[:validate] && !valid?(context)
      
      run_callbacks(context) do
        if context == :create
          key = self.class.persistence.insert(self)
        else
          key = self.class.persistence.update(self)
        end
        self.persist!
        key
      end
    end
509479
def save
      result = validate
      fail result unless result == true
      @log.debug(to_json)
      if handlerId
        @client.update_event_handler(handlerId, to_json)
      else
        @client.create_event_handler(to_json)
      end
    end
653783
def save(self):
        """"""
        check_bind(self)

        creating = self.id is None
        if creating and not self.__class__._has_schema_method("create"):
            raise MethodNotSupported("{} do not support creating.".format(self.__class__.__name__))
        if not creating and not self.__class__._has_schema_method("update"):
            raise MethodNotSupported("{} do not support updating.".format(self.__class__.__name__))

        try:
            self._resource.save()
        except HTTPError as e:
            if e.response.status_code == 400:
                err_json = e.response.json().get("errors", [])
                msg = pretty_print_error(err_json)
                raise ServerError(msg)
            elif e.response.status_code == 404:
                action = "creating" if creating else "updating"
                raise MethodNotSupported(
                    "{} do not support {}.".format(self.__class__.__name__, action)
                )
            elif e.response.status_code == 409:
                raise ServerError("This {} object already exists".format(self.__class__.__name__))
            else:
                raise e
418783
def validate(self):
        
        # Don't call the validator again, if it was already called for the
        # current input.
        if self.validation_state != ValidationState.UNKNOWN:
            return self.validation_state == ValidationState.VALID

        # Validate first. If not valid, set validation exception.
        if self.validator:
            try:
                self.validator.validate(self.document)
            except ValidationError as e:
                # Set cursor position (don't allow invalid values.)
                cursor_position = e.cursor_position
                self.cursor_position = min(max(0, cursor_position), len(self.text))

                self.validation_state = ValidationState.INVALID
                self.validation_error = e
                return False

        self.validation_state = ValidationState.VALID
        self.validation_error = None
        return True
39043
private boolean save(Document document, boolean deletion, ConcurrencyControl concurrencyControl)
        throws CouchbaseLiteException {
        if (deletion && !document.exists()) {
            throw new CouchbaseLiteException("Cannot delete a document that has not yet been saved.",
                CBLError.Domain.CBLITE, CBLError.Code.NOT_FOUND);
        }

        C4Document curDoc = null;
        C4Document newDoc = null;
        synchronized (lock) {
            mustBeOpen();
            prepareDocument(document);
            boolean commit = false;
            beginTransaction();
            try {
                try {
                    newDoc = save(document, null, deletion);
                    commit = true;
                }
                catch (LiteCoreException e) {
                    if (!(e.domain == C4Constants.ErrorDomain.LITE_CORE
                        && e.code == C4Constants.LiteCoreError.CONFLICT)) {
                        throw CBLStatus.convertException(e);
                    }
                }

                if (newDoc == null) {
                    // Handle conflict:
                    if (concurrencyControl.equals(ConcurrencyControl.FAIL_ON_CONFLICT)) {
                        return false; // document is conflicted and return false because of OPTIMISTIC
                    }

                    try {
                        curDoc = getC4Database().get(document.getId(), true);
                    }
                    catch (LiteCoreException e) {
                        if (deletion
                            && e.domain == C4Constants.ErrorDomain.LITE_CORE
                            && e.code == C4Constants.LiteCoreError.NOT_FOUND) {
                            return true;
                        }
                        else { throw CBLStatus.convertException(e); }
                    }

                    if (deletion && curDoc.deleted()) {
                        document.replaceC4Document(curDoc);
                        curDoc = null; // NOTE: prevent to call curDoc.free() in finally block
                        return true;
                    }

                    // Save changes on the current branch:
                    // NOTE: curDoc null check is done in prev try-catch blcok
                    try {
                        newDoc = save(document, curDoc, deletion);
                    }
                    catch (LiteCoreException e) {
                        throw CBLStatus.convertException(e);
                    }
                }

                document.replaceC4Document(newDoc);
                commit = true;
            }
            finally {
                if (curDoc != null) {
                    curDoc.retain();
                    curDoc.release(); // curDoc is not retained
                }
                try {
                    endTransaction(commit); // true: commit the transaction, false: abort the transaction
                }
                catch (CouchbaseLiteException e) {
                    if (newDoc != null) {
                        newDoc.release(); // newDoc is already retained
                    }
                    throw e;
                }
            }
            return true;
        }
    }
526671
def save(self):
        """"""
        if not self.is_valid():
            return self._errors
        _new = self.is_new()
        if _new:
            self._initialize_id()
        with Mutex(self):
            self._write(_new)
        return True
530755
def save(self):
        
        props = self.deflate(self.__properties__)
        query = "MATCH ()-[r]->() WHERE id(r)={self} "
        for key in props:
            query += " SET r.{0} = {{{1}}}".format(key, key)
        props['self'] = self.id

        db.cypher_query(query, props)

        return self
357685
def create(self):
        

        # Ensure that an existing document will not be "updated"
        doc = dict(self)
        if doc.get('_rev') is not None:
            doc.__delitem__('_rev')

        headers = {'Content-Type': 'application/json'}
        resp = self.r_session.post(
            self._database.database_url,
            headers=headers,
            data=json.dumps(doc, cls=self.encoder)
        )
        resp.raise_for_status()
        data = response_to_json_dict(resp)
        super(Document, self).__setitem__('_id', data['id'])
        super(Document, self).__setitem__('_rev', data['rev'])
1098947
def save_and_close_attributes(self):
        '''
        
        '''
        if not self.saveable():
            raise AttributeError("Cannot save attribute file without a valid file")
        if not self._db_closed:
            self._db_closed = True
            if not self._read_only:
                self.save_attributes()
            self._fd.close()
974375
def save(self, force=False, uuid=False, **kwargs):
        

        if not self._initialized_with_doc and not force:
            raise Exception("Cannot save a document not initialized from a Python dict. This might remove fields from the DB!")

        self._initialized_with_doc = False

        if '_id' not in self:
            if uuid:
                self['_id'] = str("%s-%s" % (self.mongokat_collection.__class__.__name__, uuid4()))

        return self.mongokat_collection.save(self, **kwargs)
665021
def save_document(document, validate = true, retries = 0, &block)
      begin
        block.call document if block
        save_document_without_conflict_handling(document, validate)
      rescue CouchRest::Conflict => e
        if block
          handle_write_conflict document, validate, retries, &block
        else
          raise CouchPotato::Conflict.new
        end
      end
    end
216007
function saveKeyValues(view, docIdsToChangesAndEmits, seq) {
  var seqDocId = '_local/lastSeq';
  return view.db.get(seqDocId)
  .catch(defaultsTo({_id: seqDocId, seq: 0}))
  .then(function (lastSeqDoc) {
    var docIds = Object.keys(docIdsToChangesAndEmits);
    return Promise.all(docIds.map(function (docId) {
      return getDocsToPersist(docId, view, docIdsToChangesAndEmits);
    })).then(function (listOfDocsToPersist) {
      var docsToPersist = flatten(listOfDocsToPersist);
      lastSeqDoc.seq = seq;
      docsToPersist.push(lastSeqDoc);
      // write all docs in a single operation, update the seq once
      return view.db.bulkDocs({docs : docsToPersist});
    });
  });
}
541365
def saveas name=nil, config={}
      unless name
        name = rb_gets "File to save as: "
        return if name.nil? || name == ""
      end
      overwrite_if_exists = config[:overwrite_if_exists] || false
      unless overwrite_if_exists
        exists = File.exists? name
        if exists # need to prompt
          return unless rb_confirm("Overwrite existing file? ")
        end
      end
      # if it has been set do not prompt. or ask only if value is :ask
      # But this should only be if there is someformatting provided, that is there 
      # is a @document
      l = @list
      # the check for document is to see if it is some old widget like textarea that is calling this.
      if @document
        if config.key? :save_with_formatting
          save_with_formatting = config[:save_with_formatting] 
        else
          save_with_formatting = rb_confirm("Save with formatting?")
        end
        if save_with_formatting
          l = @list
        else
          l = @document.native_text().map do |w| w.to_s ; end
        end
      end
      #l = getvalue
      File.open(name, "w"){ |f|
        l.each { |line| f.puts line }
        #l.each { |line| f.write line.gsub(/\r/,"\n") }
      }
      rb_puts "#{name} written."
    end
216629
function(doc) {
      try {
        localStorage.setItem(prefix + doc.id, doc.serialize());
        return true;
      } catch (error) {
        // QUOTA_EXCEEDED
        console.error("Error while saving document to local storage",
            error);
        return false;
      }
    }
478018
def save
      return true if !new_record? && !changed?
      raise Exceptions::ValidationFailedException.new(errors) if !valid?

      if !new_record?
        # If its not a new record, any changes will require a new shared
        # folder to be created, so we first destroy it then recreate it.
        destroy(false)
      end

      create
    end
876136
def save(self, data):
        """"""
        if not self.is_connected:
            raise Exception("No database selected")
        if not data:
            return False
        if isinstance(data, dict):
            doc = couchdb.Document()
            doc.update(data)
            self.db.create(doc)
        elif isinstance(data, couchdb.Document):
            self.db.update(data)
        elif isinstance(data, list):
            self.db.update(data)
        return True