PouchDB教程

PouchDB 创建批处理

批处理是PouchDB中的一组文档。 db.bulkDocs()方法用于创建文档或批处理的数组。创建文档时,如果不提供_id值,则PouchDB会代表您为批量中的所有文档生成唯一的ID。
您可以将要在PouchDB中创建的所有文档存储在数组并将其作为参数传递给此方法。此方法还接受回调(可选)函数作为参数。
语法:
db.bulkDocs(docs, [options], [callback]) 

创建批处理示例

让我们使用db.bulkDocs()方法在PouchDB中创建多个文档。文档应为JSON格式,一组用逗号(,)分隔并括在花括号({})中的键/值对。
该批次将在存储的名为" Second_Database"的数据库中创建在PouchDB服务器上。
//Requiring the package
var PouchDB = require('PouchDB');
//Creating the database object
var db = new PouchDB('Second_Database');
//Preparing the documents array
doc1 = {_id: '001', name: 'Ajeet', age: 23, Designation: 'Programmer'}
doc2 = {_id: '002', name: 'Robert', age: 24, Designation: 'Teacher'}
doc3 = {_id: '003', name: 'Abdul', age: 25, Designation: 'Mechanic'}
docs = [doc1, doc2, doc3]
//Inserting Documents
db.bulkDocs(docs, function(err, response) {
   if (err) {
      return console.log(err);
   } else {
      console.log("Documents created Successfully");
   }
});
将以上代码保存在名为" PouchDB_Examples"的文件夹中的名为" Create_Batch.js"的文件中。打开命令提示符,并使用node执行JavaScript文件:
node Create_Batch.js
输出:
PouchDB创建批次1

在远程数据库中创建批处理

您可以在远程存储在CouchDB Server上的数据库中创建批处理。为此,您必须传递要在其中创建批处理的数据库的路径。

示例

我们在CouchDB服务器上有一个名为"员工"的数据库。
PouchDB创建批次2
"员工"数据库中没有文档。
PouchDB创建批次3
让我们在"员工"数据库中创建批次。
//Requiring the package
var PouchDB = require('PouchDB');
//Creating the database object
var db = new PouchDB('http://localhost:5984/employees');
//Preparing the documents array
doc1 = {_id: '001', name: 'Lucky', age: 24, Designation: 'Teacher'}
doc2 = {_id: '002', name: 'Raman', age: 25, Designation: 'Designer'}
doc3 = {_id: '003', name: 'Albert', age: 26, Designation: 'Engineer'}
docs = [doc1, doc2, doc3]
//Inserting Documents
db.bulkDocs(docs, function(err, response) {
   if (err) {
      return console.log(err);
   } else {
      console.log("Documents (Batch) created Successfully");
   }
});
将以上代码保存在名为" PouchDB_Examples"的文件夹中的" Create_Remote_Batch.js"文件中。打开命令提示符,并使用node执行JavaScript文件:
node Create_Remote_Batch.js
输出:
PouchDB创建批次4

验证

您可以在CouchDB服务器上看到创建的文档。
PouchDB创建批次5
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4