项目作者: WebFreak001

项目描述 :
Support for more structured MongoDB databases
高级语言: D
项目地址: git://github.com/WebFreak001/MongoSchemaD.git
创建时间: 2015-11-05T01:09:39Z
项目社区:https://github.com/WebFreak001/MongoSchemaD

开源协议:

下载


MongoSchemaD

A simple library for vibe.d adding support for structured Bson
data using structs/classes and functions to simplify saving,
updating and finding Mongo documents.

Can also be used without MongoDB for Bson (de)serialization.

Example

  1. import vibe.db.mongo.mongo;
  2. import mongoschema;
  3. import mongoschema.aliases : name, ignore, unique, binary;
  4. struct Permission
  5. {
  6. string name;
  7. int priority;
  8. }
  9. struct User
  10. {
  11. mixin MongoSchema; // Adds save, update, etc.
  12. @unique
  13. string username;
  14. @binary()
  15. ubyte[] hash;
  16. @binary()
  17. ubyte[] salt;
  18. @name("profile-picture")
  19. string profilePicture = "default.png";
  20. Permission[] permissions;
  21. @ignore:
  22. int sessionID;
  23. }
  24. // implement these for this example
  25. // if you use static arrays in the functions (like using the std.digest methods)
  26. // you need to call .idup on your arrays to copy them to GC memory, otherwise
  27. // they would corrupt when leaving the stack frame. (returning the function)
  28. ubyte[] generateSalt();
  29. ubyte[] complicatedHashFunction();
  30. User registerNewUser(string name, string password)
  31. {
  32. User user;
  33. user.username = name;
  34. user.salt = generateSalt();
  35. user.hash = complicatedHashFunction(password, user.salt);
  36. user.permissions ~= Permission("forum.access", 1);
  37. // Automatically serializes and puts the object in the registered database
  38. // If save was already called or the object got retrieved from the
  39. // collection `save()` will just update the existing object.
  40. user.save();
  41. // ->
  42. // {
  43. // username: name,
  44. // hash: <binary>,
  45. // salt: <binary>,
  46. // profile-picture: "default.png",
  47. // permissions: [{
  48. // name: "forum.access",
  49. // priority: 1
  50. // }]
  51. // }
  52. return user;
  53. }
  54. // convenience method, could also put this in the User struct
  55. User find(string name)
  56. {
  57. // throws if not found, can also use `tryFindOne` to get a Nullable instead
  58. // of throwing an exception.
  59. return User.findOne(["username": name]);
  60. }
  61. void main()
  62. {
  63. // connect as usual
  64. auto client = connectMongoDB("localhost");
  65. // before accessing any MongoSchemaD functions on a struct, register the
  66. // structs using the `MongoCollection.register!T` function globally.
  67. // Links the `test.users` collection to the `User` struct.
  68. client.getCollection("test.users").register!User;
  69. }