다양한 언어 SDK 중 하나를 사용하여 웹 또는 모바일 애플리케이션에서 Couchbase를 사용하는 방법은 많이 있습니다. 하지만 PHP와 같은 백엔드 언어권이나 Objective-C와 같은 모바일 언어권을 사용하지 않는다면 어떻게 될까요? HTML, CSS, JavaScript 기능만 있는 Amazon S3와 같은 정적 호스팅 웹 서비스를 사용하는 경우에는 어떻게 될까요?
바로 여기서 PouchDB가 역할을 할 수 있습니다. 파우치DB PouchDB는 웹 브라우저에서 JavaScript를 사용하여 작동하도록 설계된 동기화 및 저장소 라이브러리입니다. Couchbase와 함께 이 라이브러리를 사용하는 데 백엔드 코드나 SDK는 필요하지 않습니다. PouchDB는 클라이언트 측 SDK의 역할을 수행하여 Couchbase Sync Gateway와 데이터를 양방향으로 복제할 수 있습니다. 하지만 PouchDB는 바닐라 JavaScript를 사용하므로, 애플리케이션이 AngularJS를 사용할 때는 어떤 일이 발생할까요?
PouchDB의 다양한 함수를 감싸서 AngularJS와 더 친화적으로 만드는 방법에 대해 살펴보겠습니다.
준비물
우리가 만들 애플리케이션에는 몇 가지 요구 사항이 있습니다. 진행하면서 어떻게 얻게 되는지 살펴보겠지만, 앞으로 무엇을 하게 될지 미리 알 수 있도록 맛보기로 몇 가지를 소개합니다.
- 간단한 HTTP 서버 등을 실행하기 위한 파이썬
- 카우치베이스 싱크 게이트웨이
- 파우치DB 4
- 앵글라스이에스 1
- AngularJS UI-Router 라이브러리 버전 0.2
- 트위터 부트스트랩 3
우리 프로젝트의 기반 다지기
코드로 들어가기 전에, 프로젝트 구조를 잡고 모든 라이브러리와 스타일을 제자리에 놓아봅시다.
컴퓨터의 어딘가에 디렉터리를 만드세요 파우치DB 그리고 루트에 다음 디렉터리들을 추가하세요:
- CSS
- 글꼴
- 자바스크립트
- 템플릿
프로젝트의 루트에 또한 다음이라는 파일을 생성해야 합니다. 인덱스.html 그리고 다음이라는 파일 sync-gateway-config.json.
이제 프로젝트에 필요한 모든 라이브러리를 다운로드해야 합니다. 다음으로 시작합니다: 트위터 부트스트랩, 최신 버전을 다운로드하여 모든 것을 배치하세요 min.css 파일들을 CSS 프로젝트의 모든 디렉토리 min.js 파일들을 자바스크립트 프로젝트의 디렉토리와 그 안의 모든 글꼴 파일 글꼴 프로젝트 디렉토리.
트위터 부트스트랩을 치워버렸으니, 다음으로는 다운로드해야 합니다. 앵글러JS 그리고 AngularJS UI-Router. 이 라이브러리들을 다운로드한 후, 다음을 배치하세요. min.js 프로젝트에 파일들을 자바스크립트 디렉토리.
다운로드할 마지막 라이브러리는 파우치DB. 다운로드한 후 min.js 파일을 다음에 놓으세요: 자바스크립트 나머지 모든 파일이 포함된 프로젝트의 디렉토리입니다.
Couchbase 싱크 가이트웨이 가져오기
이 프로젝트가 성공하려면 Couchbase 싱크 게이트웨이(Sync Gateway)가 필요합니다. 익숙하지 않은 분들을 위해 설명하자면, Couchbase 싱크 게이트웨이는 로컬 애플리케이션(AngularJS 애플리케이션)과 Couchbase 서버 사이의 데이터 처리를 담당하는 중개자 서비스입니다. 이 예제에서는 Couchbase 서버를 사용하지 않으므로, 싱크 게이트웨이가 클라우드에서 인메모리 스토리지 솔루션 역할을 하게 됩니다.
Couchbase Sync Gateway는 다음을 통해 찾을 수 있습니다. 카우치베이스 다운로드 섹션.
우리 프로젝트 구축하기
모든 파일이 제자리에 위치했으므로 이제 애플리케이션 코딩을 시작할 수 있습니다.
모든 스크립트 및 스타일 포함
모든 스타일과 스크립트를 우리에 포함시키는 것으로 시작하겠습니다 인덱스.html 파일을 여세요. 인덱스.html 파일을 생성하고 다음 코드를 포함하세요:
|
1 |
이것에서 주의해야 할 몇 가지 사항 인덱스.html 파일. 저희는 AngularJS 애플리케이션의 이름을 다음과 같이 지었습니다. 파우치앱 그리고 우리는 생소하게 보일 수 있는 태그를 사용하고 있습니다:
해당 태그는 AngularJS UI-Router의 일부입니다. 이것은 각 화면이 해당 태그로 로드되는 부분 템플릿(partial)인 단일 페이지 애플리케이션(SPA)입니다. 곧 더 이해가 될 것입니다.
AngularJS 로직 파일 생성하기
프로젝트 내부에서 자바스크립트 디렉토리, 파일 생성: app.js 다음 코드를 포함하십시오:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
앵귤러.모듈(“파우치앱”, [“ui.router”]) .실행(함수($파우치DB) { }) .설정(함수($상태제공자, $urlRouterProvider) { }) .제어기(“메인컨트롤러”, 함수($범위, $루트 스코프, $상태, $stateParams, $파우치DB) { }) |
이 파일 전반에 관해 주목해야 할 몇 가지 사항과 우리가 앞으로 할 일에 대해. app.js 파일은 우리의 모든 애플리케이션 로직이 들어갈 곳입니다. 그 안에는 다음이 있습니다. .run() 애플리케이션이 실행될 때 실행될 함수, 그 외 추가 내용 등 .config() 우리 애플리케이션의 모든 화면을 설정하는 함수(UI-Router), 그리고 .controller() 우리 특정 애플리케이션의 기능에 대한 로직을 포함할 함수.
또한 다음 사항도 유의하세요 $pouchDB 이것은 나중에 설계할 AngularJS 서비스이므로.
AngularJS 설정
AngularJS UI-Router를 사용하고 있으므로 라우트를 다음에서 설정해야 합니다. .config() 의 기능 app.js 파일. 코드는 다음과 같습니다:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
$상태제공자 .상태(“목록”, { “URL”: “/목록”, “templateUrl”: “templates/list.html”, “controller”: “메인컨트롤러” }) .상태(“item”, { “URL”: “/item/:documentId/:documentRevision”, “templateUrl”: “templates/item.html”, “controller”: “메인컨트롤러” }); $urlRouterProvider.otherwise(“목록”); |
To sum it up, we have two routes (screens) here. We have a screen for showing a list of some sort and a screen that allows us to add or update items of the list. Both routes use an AngularJS controller called MainController, but each have a different template.
The AngularJS Route Templates
Each screen needs its own HTML to be shown to the user. In your project’s 템플릿 directory, create list.html 그리고 item.html. Open the list.html and add the following code:
|
1 |
New Item |
A lot of this might look crazy, but I’ll explain it and it should make better sense. First off, we’re creating a table and looping through an object creating a new table row for each iteration. Being that this is an object we’re looping through, it will have both a key and a value which is why we have separated it. The value of this pair is also an object, which contains name information as well as email information.
The line with the edit 그리고 삭제 is taking information from the object to either delete it from storage or pass it to a different screen so we can edit it.
Now moving onto the second and last route for our application. Open the item.html 파일을 생성하고 다음 코드를 포함하세요:
|
1 |
Essentially this is just a form. We do have a save function in there that we’ll look at in the AngularJS controllers section coming next.
The PouchDB AngularJS Service
Before we go any further we need to talk about the AngularJS service for PouchDB. Otherwise, everything else is not going to make sense. We’re creating a service because we want things to be AngularJS friendly with PouchDB. We want to have reactive interfaces among other things. At the end of the app.js file, add the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
.service(“$pouchDB”, [“$rootScope”, “$q”, 함수($루트 스코프, $q) { 변수 데이터베이스; 변수 changeListener; 이것.setDatabase = 함수(databaseName) { 데이터베이스 = 새로운 파우치DB(databaseName); } 이것.startListening = 함수() { changeListener = 데이터베이스.changes({ live: 참인, include_docs: 참인 }).~에(“change”, 함수(change) { 만약(!change.deleted) { $루트 스코프.$broadcast(“$pouchDB:change”, change); } 그 외 { $루트 스코프.$broadcast(“$pouchDB:delete”, change); } }); } 이것.stopListening = 함수() { changeListener.cancel(); } 이것.sync = 함수(remoteDatabase) { 데이터베이스.sync(remoteDatabase, {live: 참인, retry: 참인}); } 이것.저장 = 함수(jsonDocument) { 변수 deferred = $q.defer(); 만약(!jsonDocument._id) { 데이터베이스.게시물(jsonDocument).그렇다면(함수(응답) { deferred.resolve(응답); }).catch(함수(오류) { deferred.reject(오류); }); } 그 외 { 데이터베이스.넣다(jsonDocument).그렇다면(함수(응답) { deferred.resolve(응답); }).catch(함수(오류) { deferred.reject(오류); }); } 반환 deferred.promise; } 이것.삭제 = 함수(documentId, documentRevision) { 반환 데이터베이스.제거(documentId, documentRevision); } 이것.얻다 = 함수(documentId) { 반환 데이터베이스.얻다(documentId); } 이것.destroy = 함수() { 데이터베이스.destroy(); } }]); |
That is a lot to take in. We’re essentially just wrapping many of the PouchDB functions. However, what matters the most here is the startListening 그리고 저장 functions.
Inside the startListening function we’re listening for changes and broadcasting them through the application using $rootScope.$broadcast. Although you haven’t seen it yet, AngularJS can pick up those broadcasts using $rootScope.$on. This makes changing the UI very easy.
In terms of the 저장 function, we are checking to see if a document id was passed to us. If no document id was passed it means that this is a new document to be inserted, otherwise it is an update.
Getting Back Into Our Controller And Run Function
Lets start with the AngularJS .run() function because it is short. Add the following code:
|
1 2 3 4 |
.실행(함수($파우치DB) { $파우치DB.setDatabase(“nraboy-test”); $파우치DB.sync(“https://localhost:4984/test-database”); }) |
Here we name the local database and we tell it that we want to sync to this remote location which is actually our Couchbase Sync Gateway. This sync happens continuously after we call it. By continuously I mean changes will be replicated between application and server for as long as the application is open.
Jumping into the controller code, add the following:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
.제어기(“메인컨트롤러”, 함수($범위, $루트 스코프, $상태, $stateParams, $파우치DB) { $범위.items = {}; $파우치DB.startListening(); $루트 스코프.$~에(“$pouchDB:change”, 함수(event, 데이터) { $범위.items[데이터.의사._id] = 데이터.의사; $범위.$apply(); }); $루트 스코프.$~에(“$pouchDB:delete”, 함수(event, 데이터) { 삭제 $범위.items[데이터.의사._id]; $범위.$apply(); }); 만약($stateParams.documentId) { $파우치DB.얻다($stateParams.documentId).그렇다면(함수(결과) { $범위.inputForm = 결과; }); } $범위.저장 = 함수(이름, lastname, 이메일) { 변수 jsonDocument = { “이름”: 이름, “lastname”: lastname, “email”: 이메일 }; 만약($stateParams.documentId) { jsonDocument[“_id”] = $stateParams.documentId; jsonDocument[“_rev”] = $stateParams.documentRevision; } $파우치DB.저장(jsonDocument).그렇다면(함수(응답) { $상태.go(“목록”); }, 함수(오류) { 콘솔.로그(“ERROR -> “ + 오류); }); } $범위.삭제 = 함수(아이디, rev) { $파우치DB.삭제(아이디, rev); } }) |
The application is already syncing, so we need to listen for any changes. Here is the $rootScope.$on I mentioned earlier. We have two of them because in one we are listening for changes (create or update) and in the other we are listening for deletes.
If the list.html page routed us here for an update, then we’ll have a document id passed. In this scenario we can do a lookup and get the data for that particular document id to display in the form rather than leaving it blank which is the default.
Finally we have our 저장 그리고 삭제 functions.
The Sync Gateway Configuration
PouchDB and AngularJS is only half the story here. Sure they will create a nice locally running application, but we want things to sync. The Couchbase Sync Gateway is our endpoint for this and of course PouchDB works great with it.
프로젝트 내부에서 sync-gateway-config.json file, add the following:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
{ “로그”:[“CRUD+”, “REST+”, “Changes+”, “Attach+”], “데이터베이스”: { “test-database”: { “서버”:“walrus:data”, “sync”:` 함수 (의사) { channel (의사.채널); } `, “사용자”: { “손님”: { “비활성화됨”: 거짓, “관리자_채널”: [“*”] } } } }, “CORS”: { “Origin”: [“https://localhost:9000”], “LoginOrigin”: [“https://localhost:9000”], “Headers”: [“Content-Type”], “MaxAge”: 17280000 } } |
This is one of the most basic configurations around. A few things to note about it:
- It uses walrus:data for storage which is in memory and does not persist. Not to be used for production.
- All data is synced via the GUEST user, so there is no authentication happening here, but there could be
- We are fixing CORS issues by allowing requests on localhost:9000
Testing The Application
At this point all our code is in place and our Sync Gateway is ready to be run. Start up the Sync Gateway by running the following in a command prompt or terminal:
|
1 |
/경로/-로/sync/gateway/bin/sync–gateway /경로/-로/project/sync–gateway–설정.json |
Now this is where Python comes into play. You cannot just open the HTML files in a web browser. They must be served to prevent CORS issues. From the command prompt or terminal, with the project as your current working directory, run the following:
|
1 |
python –m SimpleHTTPServer 9000 |
Visit https://localhost:9000 in your web browser and check it out!
결론
You now saw how to create a web application that can sync with Couchbase using nothing more than AngularJS and PouchDB. No backend SDKs were required.
You can obtain the full working source code to this blog post via our Couchbase Labs GitHub repository.
작가
41개의 응답
-
Will N1QL support joining from 2 buckets on some common field? I have 2 buckets, Documents in both bucket has acct_id field. Can I join both bucket on acct_id to get result?
-
Thanks for this great tutorial.
Sir, i would like to use offline
storage like PouchDB to store and retrieve images and i have been
battling with it for quite some time now. I followed the home website of PouchDB but i wasn’t able to save a single pic to it
And i would be so grateful, if you can put me through with a simple illustration.
Many thanks-
Why not convert your images to base64 strings and store the strings?
-
Ok sir. Let me do that.
Thank you. -
As advised, i use angular.tojson on the image data from the camera, and stored the result on pouchdb.
However, i tried to retrieve the image and display but no success. The image is part of an object array with a reference name. Though, i use ng-repeat to loop through the object to extract the name and date of birth, but i don’t know how to convert back the image to its original form in the expression field i.e {{}}
Thank you sir.-
When you say camera, if you’re talking about Ionic Framework, have you seen this?:
https://blog.nraboy.com/2014/0...
More specifically there is this line in the example:
1$범위.이미지URI = "data:image/jpeg;base64," + 이미지 데이터;To display a base64 image, you need to assign your HTML
이미지tag “data:image/jpeg;base64” otherwise the tag won’t understand the data you are passing:1<이미지 엔지-보여주다="imgURI !== undefined" 엔지-소스="{{imgURI}}"<Hopefully that helps.
Best,
-
-
-
-
Nic, thanks for the blog tutorial. your controller coding style is different than what i learned and i was wondering if you would help in adding another page link to the app? I attempted to copy and duplicate your controller and that did not work. thank you
-
Nic, having difficulties syncing with “sync gateway” back to my Couchbase Server. Do you have any tips? I do have an error that my “cors” is not turned on. Could that be why?
-
Could be, but that is usually a browser based problem.
Can you please provide more details in regards to your setup, and what is happening. The more information I have, the better I can help.
Best,
-
Nic, I mostly used the code per your instructions. My setup is developing a angular PouchDB to Couchbase app on my MS Surface Pro 3. this is my development device. My Couchbase server is on our Office server. Most of my development is when I am on same network as the CouchBase server and the main purpose is for my program to work in the field with limited connectivity with the office server.Please let me know if there is more you would like to know. Thanks
-
Sorry for my late response, I was on vacation for the holidays.
I’m a bit confused by the information you gave me. Can you clear some things up?
1. Is the web application (PouchDB, Angular, ect) running on your Surface Pro?
2. Is Couchbase Sync Gateway running on your Surface Pro or on your office server?
3. Is your Couchbase Server behind a firewall? In other words, regardless of where your Sync Gateway is hosted, does it have firewall permission to access Couchbase Server?Best,
-
1. the application will be running on our supervisors (30 of them) surface pro’s, laptops.
2. Couchbase and the sync gateway is on the server at the office.
3. yes we have permissions to access the CouchBase server.
i think i have it almost setup, i am getting this error? “400 illegal database name: TCS-Mobile”
TCS-Mobile is the correct name of my bucket.
-
Is this error via Sync Gateway or the console logs of the web application?
-
console logs.
-
Can I request that you follow my tutorial exactly? My guess is you’ve got something custom to your setup that may not be correct.
You might also look at this:
https://www.youtube.com/watch?…
Regards,
-
-
-
-
Hi Nic,
You seem to have a way of making the complex understandable.
I am start-up “product owner” (scrum) and haven’t got my IT team in place yet. We will be building a mobile (not native) app and a web browser app to work with Couchbase server.
“This is where PouchDB might come into play. PouchDB is a synchronization and storage library designed to work in a web browser using JavaScript.”
Can Couchbase Lite / Mobile work in a web browser using JavaScript similar to what you have done using PouchDB?
Thank you,
Jim
PS. I should have mentioned that I do not need offline capability for the web app.
-
Have you seen this?:
Great tutorial, I am in the middle of an offline first project at the moment so this is perfect. I am having a few issues with the CORS though. I ended up grabbing your code from Github to ensure I didn’t have any silly typos but the issues still persist.
I am using Chrome on a Mac.
When I start the sync gateway I get the following:
MacBook-Pro:~ leigh$ couchbase-sync-gateway/bin/sync_gateway Dropbox/wwwroot/offlinefirst/sync-gateway-config.json
19:52:18.109745 Enabling logging: [CRUD+ REST+ Changes+ Attach+]
19:52:18.109826 ==== Couchbase Sync Gateway/1.0.4(34;04138fd) ====
19:52:18.109840 Configured Go to use all 8 CPUs; setenv GOMAXPROCS to override this
19:52:18.109858 Opening db /test-database as bucket “test-database”, pool “default”, server <walrus:data>
19:52:18.109893 Opening Walrus database test-database on <walrus:data>
19:52:18.110497 Changes+: Notifying that “test-database” changed (keys=”{_sync:user:}”) count=2
19:52:18.110505 Reset guest user to config
19:52:18.110516 Starting admin server on 127.0.0.1:4985
19:52:18.113169 Starting server on :4984 …
2016/01/25 19:52:20 Walrus: Warning: Couldn’t save walrus bucket: open data/walrustemp741838838: no such file or directory
and in the browser I get this:
XMLHttpRequest cannot load https://localhost:4984/test-database/?_nonce=1453751478847. A wildcard ‘*’ cannot be used in the ‘Access-Control-Allow-Origin’ header when the credentials flag is true. Origin ‘https://localhost:9000’ is therefore not allowed access.
pouchdb-4.0.1.min.js:9 PouchDB error: the remote database does not seem to have CORS enabled. To fix this, please enable CORS: https://pouchdb.com/errors.html...
-
Interesting!
Did you make sure to serve your AngularJS project rather than just opening the index file via the Finder? If you’re serving your project and you’re trying to use it via localhost:9000, can you tell me what version of Sync Gateway you’re using?
Best,
-
Thanks for responding Nic,
I tried with Sync Gateway 1.0.4 and 1.1 and also swapped between Pouch 4.0.1 and Pouch 5.2.0 without any luck. I definitely served the project using the Python server too. In the end I followed your YouTube tutorial ( https://www.youtube.com/watch?… which had a very slight change in the sync-gateway-config.json file compared to this tutorial.
When I used ‘walrus:data’ as per this tutorial I had the CORS issue but when I followed the Youtube one and used “server”:”https://localhost:8091″ it was ok.
At least I’m up and running now!
One last question, should this handle bi-directional sync as it is? I will have an Electron app, mobile app and web app all syncing to the Couchbase database so will need each PouchDB to push and pull
-
그 sync function in the $pouchDB service will handle bi-directional sync.
In my video I used localhost:8091 because I had it connected to my live Couchbase Server instance. In this article I had Sync Gateway set up to use the development-only walrus temporary storage. Odd that the CORS issues went away when you switched to Couchbase Server, but I’m happy that you got it working.
If you haven’t already, don’t forget to do a search for the Electron tutorial I made that extends this post.
Best,
-
-
I keep getting a CORS error when trying to sync a PouchDB database. I’ve tried the above sync-gateway-config.json and the version found in the Couchbase Sync Gateway docs here:
https://developer.couchbase.com...
In both cases, I get the following error:
XMLHttpRequest cannot load https://localhost:4985/test-database/.
No ‘Access-Control-Allow-Origin’header is present on the requested
resource. Origin ‘https://localhost:3000’ is therefore not
allowed access.
I posted this issue to StackOverflow, but no one has tried submitting an answer yet.
https://stackoverflow.com/quest...
-
I assume you’re using the following:
1“CORS”: {<br< “Origin”: [“https://localhost:9000”],<br< “LoginOrigin”: [“https://localhost:9000”],<br< “Headers”: [“Content-Type”],<br< “MaxAge”: 17280000<br<}Your error says you are trying to access via port 3000. Have you changed the port inside the CORS section of Sync Gateway from 9000 to 3000?
Best,
-
Thank you for getting back to me. I did. In my sync-gateway-config.json file, both “Origin” and “Login Origin” are set to port 3000. I’m stuck at the moment and I’m not sure what else to try. The question I posted to Stack Overflow has no answers yet either.
-
I sent an email to our mobile team. They should follow up on this post soon. I personally don’t see what can be wrong, but they may have a different perspective.
Best,
-
It looks like you’re trying to hit the Sync Gateway admin port, which doesn’t support CORS, as far as I know. Have you tried targeting the public port (4984)?
-
That was the problem. I was using 4985 for some reason. Not sure why. Thank you for your help.
-
-
-
Hi Nic, Great tutorial!!
How would you integrate “PouchDB” with Spring Framework? So you can use Spring Security, other Java libs and expose a Restful API (maybe just a dummy wrapper on top of Couchbase). My main goal is to have a AngularJs client with offline autonomy, and auto-sync capabilities, but since I have a lot of modules written in Java and I need to integrate other libraries I would love to combine all this with a Spring Framework App in the backend.
I have read also your tutorial https://www.couchbase.com/deve… , but I don’t know what is the best approach to integrate it with PouchDB.
Any advice and suggestions will be greatly appreciated.
Thanks,
-
Hey @delkan@delkant:disqus,
What if you used PouchDB as the model in your MVC setup where PouchDB and Sync Gateway are in charge of all data? Then you could keep your existing Java application for logic processing and rendering.
If you needed further integration, the Couchbase Sync Gateway has a RESTful API that you can communicate with via your Java code. You can also manage custom authentication with Sync Gateway and your Java server.
It might help me to get a more specific story on the things you’re trying to do.
Best,
-
Actually, it is a good idea and works for me, but I rather prefer to use Spring security because I have all my users already on it. I have used in the past this http proxy( https://github.com/mitre/HTTP-… ) to secure solr’s http requests with spring-security, I just run a test with the Sync Gateway as well, so only Spring-security authenticated users could access to the gateway. It worked great! Another thing I like here is that I can expose just at the bucket level (based on the url), all this using spring security and on the same port where my app is, just defining a new end point to serve cloudbase sync gateway.
-
Hi Nic,
Again nice tutorial. I have a question here.
According to PouchDB documentation https://pouchdb.com/adapters.h...
Couchbase Sync Gateway **support is in progress**. It will work, but you may run into issues, especially with attachments.
Because the support is in progress I am wondering if you can use PouchDB Server with Couchbase instead. I haven’t find documentation about this but since both databases are implemented using a CouchDB-like protocol maybe they are compatible. Could please you confirm this?.
Do you always need a Sync Gateway or something like PouchDB Server to access to a couchdb-like db from PouchDB?
I am new on this, so I am sorry if my questions make no sense to you.
Thank you,
I’m getting an error when I use the sample code. The controller sets up listeners each time the list view loads and it causes the error below:
pouchdb.js:141 (node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.
Not quite an Angular ninja, but I would guess that that bit of code needs to be moved to a service.
Hi Sir !!
I wanted to develop the above application with CouchDB instead of Couchbase ? Is it the same like above ? which one is prefer, but mostly I am looking for CouchDB ? or do I need to do any modifications in the above code ? Can you provide any links or resources to develop with CouchDB ?
Thanks in advance.
-
You’ll have a much easier time with Couchbase. It is more feature rich and easier to use.
Sir I have to develop a POS application that would be offline and sync data when user have access to internet. I want to know that How couchbase handles the conflicting states. e.g. Let there is sale happened on POS station 1 for item A. customer came with 2 quantities of Item A. At the same time station 1 was offline. and Local data show only 1 quantity remaining for Item A. But Actually sales manager had refilled the stock some time ago when station 1 was offline. it means that stock refill will not showed on station 1 until database go into sync. My question is How This scenario will be handled in offline / online db states?
-
The revision history is maintained every time a document changes. So for example when you save your document the first time, it may look something like this:
1-ad2348fd
Where 1 is the revision and the rest is the hash associated with the save.
If you end up with a document that shares the same id and same revision number, but different hashes, a conflict indicator will be provided. At this point, you can query the revision history for the document i.e. look at both revision entries of the same depth (or deeper) and apply your business logic to see which save should win.
Should you run into the scenario where one device ends up with a higher revision history number, i.e the offline device saved 100 times, the higher revision save will win without conflict. However, you can always look through the revision history and apply further business logic.
Does this answer your question?
Best,
-
Not completely. The scenario I provided , I ran into issue when offline station got sales order (2 items of Product A) which way more than what its local DB state (Only 1 Items remaining of product A). In this scenario how can sales transaction carried out while station (pos app) is in offline mode. The Only business solution i could think is to go into negative items for the time period when app is offline. because 1-2 = -1; and as soon Internet available I sync the state and manage the conflicts as you stated. can you present any better solution ?
-
I am really not sure what you’re saying. Want to try again?
-
-
HI Nic,
Great tutorial. Very well explained.
i wanted to point out, while injecting the AngularJs UI router, in app.js, inject [“ui.router”] instead of [“ui-router”] to avoid the injectormodulerr error.
Thanks again
HI Nic,
MY apologies, i was the one who had mis-read. You had injected correctly.
Now that SyncGateway doesn’t support CouchDB replication protocol this tutorial seems to be invalid.

댓글 남기기
댓글을 달기 위해서는 로그인해야합니다.