more bson docs

This commit is contained in:
Joannis Orlandos 2018-01-02 15:10:49 +01:00
parent b8273b364a
commit dcc1c670bc
1 changed files with 100 additions and 1 deletions

View File

@ -33,7 +33,7 @@ For this reason, both `Document` variants are the same struct type and behave th
You can subscript a dictionary-like document with an integer, and an array-like document by it's key.
## Usage
# Usage
The root type of any BSON structure is a `Document`, please note that MongoDB entities **must** be a dictionary-like.
@ -51,6 +51,105 @@ var arrayDocument: Document = []
var dictionaryDocument: Document = [:]
```
## Accessing Dictionary Documents
To access a dictionary document you must subscript with a key:
```swift
let username = dictionaryDocument["username"] // Primitive?
```
The return type is a Primitive type, which is a protocol.
## Accessing Array Documents
To a
## Primitives
To access the concrete type of the primitive you must either cast the primitive to a concrete type or loosely unwrap the type.
For the purpose of demonstration we're assuming the following Document:
```swift
var doc: Document = [
"_id": ObjectId(),
"username": "Joannis",
"admin": true,
"year": 2018
]
```
### Casting
Casting is used when you want exactly that type. A good example is a `String`.
```swift
let username = doc["username"] as? String // String?
print(username) // Optional("Joannis")
```
The following will be nil because they're not a `String`.
```swift
let _id: = doc["_id"] as? String // String?
print(_id) // nil
let admin = doc["admin"] as? String // String?
print(admin) // nil
let year = doc["year"] as? String // String?
print(year) // nil
```
### Loosely Converting
Converting is useful when you don't care about the specifics.
For example, when exposing data over JSON.
```swift
let username = String(lossy: doc["username"]) // String?
print(username) // Optional("Joannis")
```
This converts types to a String when it's sensible:
```swift
let _id: = doc["_id"] as? String // String?
print(_id) // Optional("afafafafafafafafafafafaf")
let admin = doc["admin"] as? String // String?
print(admin) // Optional("true")
let year = doc["year"] as? String // String?
print(year) // Optional("2018")
```
## Codable
BSON has highly optimized support for Codable through `BSONEncoder` and `BSONDecoder`.
```swift
struct User: Codable {
var _id = ObjectId()
var username: String
var admin: Bool = false
var year: Int
init(named name: String, year: Int) {
self.username = name
self.year = year
}
}
let user = User(named: "Joannis", year: 2018)
let userDocument = try BSONEncoder().encode(user)
let username = userDocument["username"] as? String
print(username) // Optional("Joannis")
let sameUser = try BSONDecoder().decode(User.self, from: userDocument)
print(sameUser.username) // "Joannis"
```