更新PFObject无法正常工作

时间:2018-10-16 10:47:10

标签: ios swift mongodb heroku parse-server

在这里,我试图在集合中的每个文档上设置一个状态字段(在Parse-Server / Heroku的mongoDB中)。 下面的代码不是很复杂,但是由于某种原因它失败了。我希望能有新的眼光指出问题所在。

let query = PFQuery(className: "Book_List")
query.limit = 1024
query.findObjectsInBackground {
    (objects:[PFObject]?, error:Error?) -> Void in
    if (error == nil && objects != nil) {
        for book in objects! {
            book.setObject("0", forKey: "status")
            book.saveInBackground {
                (success: Bool, error: Error?) in
                if !success {print("FAILED.")} else {print("OK-OK.")}
                if error != nil {print("Error = \(String(describing: error))")}
            }
        }
    }

    if error != nil {
        print("Error = \(error.debugDescription)")
    }

    if objects == nil {
        print("We haven't found anything on Parse!!")
    }
}

我希望它可以运行并在每个循环上设置一个字段({“ status”:“ 0”})。但是我只能在调试控制台中看到这一点:

FAILED.
Error = Optional(Error Domain=Parse Code=101 "Object not found." UserInfo={code=101, temporary=0, error=Object not found., NSLocalizedDescription=Object not found.})
... [Error]: Object not found. (Code: 101, Version: 1.17.1)

由于我使用PFQuery-findObjectsInBackground获得了对象,所以它们存在于某个地方。 那么为什么我会收到此错误消息?

1 个答案:

答案 0 :(得分:0)

而不是单独保存每本书,请尝试使用+saveAllInBackground:block:

批量保存
let query = PFQuery(className: "Book_List")
query.limit = 1024
query.findObjectsInBackground { (objects:[PFObject]?, error:Error?) in
    if error == nil,
       let objects = objects {
        for book in objects {
            book.setObject("0", forKey: "status")
        }
        PFObject.saveAllInBackground(objects: objects) { (success: Bool, error: Error?) in
            if !success { print("FAILED.") } else { print("OK-OK.") }
            if error != nil { print("Error = \(String(describing: error))") }
        }
    }

    if error != nil {
        print("Error = \(error.debugDescription)")
    }

    if objects == nil {
        print("We haven't found anything on Parse!!")
    }
}