PouchDB 更新文档
可以使用(_rev)更新PouchDB中的文档。当我们在PouchDB中创建文档时,将生成_rev。它称为修订标记。 _rev的值是唯一的随机数,每次我们对文档进行更改时,_rev的值都会更改。
要更新文档,我们必须检索要更新的文档的_rev值。
现在,将要更新的内容与检索到的_rev值一起放在新文档中,最后使用put()方法将此文档插入PouchDB中。
更新文档示例
首先从文档中检索数据以获取其_rev编号。
使用读取文档方法。
{ _id: '001',
_rev: '1-99a7a80ec2a74959885037a16d57924f' }
name: 'Ajeet',
age: 28,
designation: 'Developer' }
现在使用_rev并将" age"的值更新为24、请参见以下代码:
//Requiring the package
var PouchDB = require('PouchDB');
//Creating the database object
var db = new PouchDB('Second_Database');
//Preparing the document for update
doc = {
age: 24,
_id: '001',
_rev: '1-99a7a80ec2a74959885037a16d57924f'
}
//Inserting Document
db.put(doc);
//Reading the contents of a Document
db.get('001', function(err, doc) {
if (err) {
return console.log(err);
} else {
console.log(doc);
}
});
将以上代码保存在名为" PouchDB_Examples"的文件夹中的名为" Update_Document.js"的文件中。打开命令提示符,并使用node执行JavaScript文件:
输出:
{ age: 24,
_id: '001',
_rev: '2-b26971720f274f1ab7234b3a2be93c83' }
更新远程数据库中的文档
您可以更新远程存储在CouchDB Server上的数据库中的现有文档。为此,您必须传递包含要更新的文档的数据库的路径。
示例
我们有一个名为" employees"的数据库在CouchDB服务器上。
通过单击"员工",您会发现它具有一个文件。
让我们更新ID为" 001"的文档的名称和年龄存在于数据库"员工"中并存储在CouchDB服务器上。
更新:
<!--Name: Ajeet to Aryan
Age: 28 t0 25-->
//Requiring the package
var PouchDB = require('PouchDB');
//Creating the database object
var db = new PouchDB('http://localhost:5984/employees');
//Preparing the document for update
doc = {
"_id": "001",
"_rev": "3-276c137672ad71f53b681feda67e65b1",
"name": "Aryan",
"age": 25
}
//Inserting Document
db.put(doc);
//Reading the contents of a Document
db.get('001', function(err, doc) {
if (err) {
return console.log(err);
} else {
console.log(doc);
}
});
将以上代码保存在名为" PouchDB_Examples"的文件夹中的名为" Update_Remote_Document.js"的文件中。打开命令提示符,并使用node执行JavaScript文件:
node Update_Remote_Document.js
输出:
{ _id: '001',
_rev: '4-406cbc35b975d160d8814c04d64bafd3',
name: 'Aryan',
age: 25 }
您还可以看到该文档已在CouchDB服务器上成功更改。
