connection.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2015 The MemDB Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  12. // implied. See the License for the specific language governing
  13. // permissions and limitations under the License. See the AUTHORS file
  14. // for names of contributors.
  15. 'use strict';
  16. // npm install memdb-client
  17. // run with node >= 0.12 with --harmony option
  18. // We assume you have started shard 's1' on localhost:31017
  19. var memdb = require('memdb-client');
  20. var P = memdb.Promise;
  21. var should = require('should');
  22. var main = P.coroutine(function*(){
  23. // Create a new connection
  24. var conn = yield memdb.connect({host : '127.0.0.1', port : 31017});
  25. // Get player collection
  26. var Player = conn.collection('player');
  27. var player = {_id : 'p1', name : 'rain', level : 1};
  28. // remove if exist
  29. yield Player.remove(player._id);
  30. // Insert a doc
  31. yield Player.insert(player);
  32. // Commit changes
  33. yield conn.commit();
  34. // Update a field
  35. yield Player.update(player._id, {$set : {level : 2}});
  36. // Find the doc (only return specified field)
  37. (yield Player.find(player._id, 'level')).should.eql({level : 2});
  38. // Rollback changes
  39. yield conn.rollback();
  40. // Data restore to last commited state
  41. (yield Player.find(player._id, 'level')).should.eql({level : 1});
  42. // Remove doc
  43. yield Player.remove(player._id);
  44. // Commit change
  45. yield conn.commit();
  46. // close connection
  47. yield conn.close();
  48. });
  49. if (require.main === module) {
  50. main().finally(process.exit);
  51. }