Swift couchebase-lite save CBLModel document problem


#1

Hello everyone, I got problems with saving/retrieving CBLModel document.

Here is what I do:

  1. create model

class TestModelUser: CBLModel {
var userName:NSString?
}

  1. create and save
    let userModel:TestModelUser = TestModelUser(newDocumentInDatabase: db)
    userModel.userName = "test user name 10"
    userModel.setValue(NSStringFromClass(TestModelUser), ofProperty: "type")
    let saved = userModel.save(&error)
    if saved {
        println("saved")
    }else{
        if let err:NSError = error {
            println(err.localizedDescription)
        }
    }
  1. retrive
    let dbView:CBLView = db.viewNamed("userView")
    dbView.setMapBlock({ (document, emit) -> Void in
        emit(document["_id"], document)
        if let docType = document["type"] as? String {
            if docType == NSStringFromClass(TestModelUser) {
                emit(document["_id"], document)
            }
        }
        }, version: "5")
    let queryResult1:CBLQueryEnumerator = db.viewNamed("userView").createQuery().run(&error)
    for row:CBLQueryRow in queryResult1.allObjects as [CBLQueryRow] {
        let user:TestModelUser = TestModelUser(forDocument: row.document)
        if let uName = user.userName {
            println(uName)
        }
    }

and I got “user.userName” always nil.
Maybe I save document incorrect?


#2

You need to declare the property as dynamic so CBLModel will know it’s persistent (same as with Core Data.) The Swift syntax for that is @NSManaged.


Couchbase Lite returns Duplicate Documents
#3

Many thanks jens!! :smile:


#4

Hey, i tried like this, but i’m getting duplicate data.


#5

Guys, i got solution, if we use emits multiple times on createView, we will get multiple rows on single CBLQueryRow.
@nils22 please check your code.

let dbView:CBLView = db.viewNamed(“userView”)
dbView.setMapBlock({ (document, emit) -> Void in
emit(document["_id"], document) //No need of this line, it cause multiple rows on single document
if let docType = document[“type”] as? String {
if docType == NSStringFromClass(TestModelUser) {
emit(document["_id"], document)
}
}
}, version: “5”)