What is the process for transferring a document from one database to another in couchDB?

Is it necessary to load a couchDB JSON document to the client first and then post it to another couchdb database in order to copy it from one db to another? Or is there a server-side method that can achieve this?

Reference The copy command is non-standard HTTP and only works within one database.

Answer №1

Affirmative, transferring data is restricted to within a single database; however, you have the option to duplicate individual or multiple documents:

curl -X POST http://localhost:5984/_replicate -H "Content-Type: application/json" -d '{"source": "db_a", "target":"db_b", "doc_ids": ["foo"]}'

Nevertheless, modifying the document ID is not possible in this scenario as it is with COPY. To achieve this, first make a copy of the document using COPY, replicate it, and then delete it from the source if necessary. By making three HTTP API calls and utilizing server-side methods, you can avoid loading document content onto the client side. The decision to opt for this approach, instead of implementing copy-logic on the client side, rests with you.

Answer №2

Utilizing node.js along with the request module.

Prior to running this code, ensure that the target document is present in the database and that the source attachment exists as well.

var originAttachment = 'somefile.txt'
var originDocId = '1somecouchdbid';
var origindb = 'http://localhost:5984/db1';

var destinationAttachment = 'somefile.txt'
var destinationDocId = '2somecouchdbid';
var desinationdb = 'http://localhost:5984/db2';

var uridestination = desinationdb + "/" + destinationDocId;

request(uridestination, function(err, res, body){

if(err){
    throw err;
}

var doc = JSON.parse(body);

var origin =  origindb + '/' + originDocId + '/' + encodeURIComponent(originAttachment);

var optionsOrigin = {
    url: origin
};

var uridestination = desinationdb + '/' + destinationDocId + '/' + encodeURIComponent(destinationAttachment) + '?rev=' + doc._rev;

var optionDestination = { 
    url: uridestination,
    method: 'PUT',
    headers: {
        'Content-Type': false
    }
};

request(optionsOrigin)
.pipe(request(optionsDestination, function(err, res, body){
    if(err){
        throw err;
    }
    console.log(body);        
}));
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently compacting JSON data within a Struct in Golang

package questionnaire import ( "encoding/json" ) type Items []Item type CreateData struct { Items []Item } type Item struct { Id enter code herestring `json:"id" required:"true"` CompCd string `json:"compCd" required ...

AJAX response from open cart is returning null JSON data

Hey there, I'm having a problem with my ajax request. It seems like I keep receiving a null value for json. Let me show you the JavaScript code... <script> $(document).ready( function() { $('#donate-box-submit').on('click' ...

Scala can read, write, and format data for non-case classes

When it comes to serializing a regular class in Scala, I'm familiar with how to serialize a case class using the simple implicit val caseClassFormat = Json.format[CaseClass] However, I'm unsure about how to go about serializing a regular class. ...

Navigating through a table using jQuery to find a specific element

There are form input elements within an HTML table structured like this: <table> <thead> .... </thead> <tr> <td><input type="text" name="n_time" id="5030c9261eca0" value="2012" /></td> ...

Determine the mean value of an element within a specific column of arrays containing JSON data stored in a PostgreSQL database

Within my postgres table, I have a column that stores JSON data in the form of an array represented as a string. Here is an example: [ {"UsageInfo"=>"P-1008366", "Role"=>"Abstract", "RetailPrice"=>2, "EffectivePrice"=>0}, {"Role"=>"Text ...

Generate a fresh JSON object by adjusting JSON data in Angular 6

Here is a sample JSON structure: [ { "Key": "doc/1996-78/ERROR-doc-20200103.xlsx" } }, { "Key": "doc/1996-78/SUCCESS-doc-20200103.xlsx" }, { "Key": "doc/1996-78/PENDING-doc-20200103.xlsx" } ] I need to split the values of the K ...

Using Ajax to trigger JSON-formatted HTML output

Issue with Populating Modal Window I am encountering difficulties while trying to populate a modal window dynamically with extended information retrieved from a mySQL database. Despite attempting various methods such as nested arrays, while loops, and for ...

Converting JSON arrays to integers from strings in JavaScript: A step-by-step guide

When my application receives a Json string from the server (written in Java), I am faced with an issue when retrieving the data in JavaScript. The current format of the data looks like this: var data = [{"value":"3","label": "17 hr"}, {"value":"2", "labe ...

Exploring ways to access a nested JSON object | Showing Orders in a Laravel E-commerce Platform

{"**6732987ae9ac9ac3d465ea993bf9425c**": {"rowId":"6732987ae9ac9ac3d465ea993bf9425c","id":14,"name":"Stanley Metz","qty":2,"price":2039,"weight":550,"options&quo ...

What is the process for displaying an Array in JSON format?

Here's what I have: @array.inspect ["x1", "x2", "adad"] I want to reformat it like this: client.send_message(s, m, {:id => "x1", :id => "x2", :id => "adad" }) client.send_message(s, m, ???????) Is there a way for @array to ...

Converting the PHP encoded Postgresql query result into a stringified array

I have a SQL query that transforms the result into JSON format. SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM ( SELECT 'Feature' As type, ST_AsGeoJSON(geom)::json As geometry, ro ...

Convert the value into boolean using Jackson JSON parsing, whether it is TRUE or FALSE

Currently, I am utilizing Jackson annotations to convert JSON responses into POJO objects. Initially, I had been using a boolean variable in the POJO for mapping values of "true" and "false" from the JSON data. However, an issue arose when the JSON start ...

Utilize PHP to transform JSON data into JavaScript

Hello, I am a newcomer to Stackoverflow and I need some assistance. My issue involves converting JSON with PHP to JavaScript. I am using PHP to fetch data from a database and create JSON, which I then want to convert for use in JavaScript as an object (obj ...

Converting complex JSON structures to Java objects with Jackson's dynamic nested parsing

i'm struggling with parsing json data I have a json string that contains nested elements and I need to convert it into a java object. The structure of the string is quite complex and dynamic, so I'm wondering how to efficiently handle this using ...

Utilizing JQuery to display JSON data on a data table using Ajax

Seeking guidance on jQuery, I am diving into a new datatable venture with preloaded data. Upon searching, the goal is to update the table by removing existing data and displaying only the search results. My attempt so far includes: app.common.genericAjaxC ...

Instructions for creating a histogram using predetermined bin values

After searching, I noticed that most tutorials on creating histograms with matplotlib focus on plotting histograms for unbinned data using the hist function. How can I go about drawing a histogram from pre-binned data? To provide more context, here is the ...

Loop through JSON results in Ionic using Angular

I am struggling to retrieve data from a JSON file in Object format using Typescript. When I try to fetch the data from the API, it doesn't display as expected. Typescript this.http.get('http://example.com/api') .subscribe((data) => { ...

Guide to transforming a file from a str class type to a Python dictionary

Below is the code snippet I have written: import json with open('json_data.json') as json_file: df = json.load(json_file) This code opens a JSON file that looks like this: {'api_version': None, 'kind': None, 'metad ...

Place the id in the queue just like you would when adding to your cart

After successfully creating model schemas for users and products and implementing simple CRUD operations, my next project involves creating a model schema for orders. In this new model schema, I plan to push the userId and projectId into an array in a spec ...

Converting a PHP array to JSON in the specific format that is needed

I am looking to create a PHP array by fetching data from a MySQL query and then convert it into JSON using a loop. The SQL query I am using looks like this: $arDados = array(); $result = $conexao->sql("SELECT * FROM sys_fabrica WHERE fl_ativo = 1 ORDER ...