iosswiftmongodbmongodb-realm

mongoDB iOS Swift SDK modify array?


I have my data model object here:

class Tiktoks: Object {
    @objc dynamic var _id: ObjectId = ObjectId.generate()
    @objc dynamic var _partition: String = ""
    @objc dynamic var category: String = ""
    @objc dynamic var date: Date = Date()
    let tiktoks = RealmSwift.List<String>()
    override static func primaryKey() -> String? {
        return "_id"
    }
    
    convenience init(partition: String, category: String) {
        self.init()
        self._partition = partition;
        self.category = category;
    }
}

I have no problem modifying _partition and category, but since the tiktoks list is defined by let, it wouldn't work if I put it in the convenience init function for me to be able to modify it. I tried putting @objc dynamic var in front of it but it says Property cannot be marked @objc because its type cannot be represented in Objective-C.

Is there any way to modify an array using the mongoDB iOS Swift SDK?


Solution

  • I ended up making a function in MongoDB Realm.

    exports = function(category, url){
      
      var collection = context.services.get("mongodb-atlas").db("database").collection("collection")
      
      collection.updateOne(
        { category: category },
        { 
          $push: { 
              tiktoks: {
              $each: [ url ], 
              $position: 0
            }
          },
          $set: {
            date: new Date()
          }
        },
        )
      
      return "done"; // not supposed to return string I think, has to return "non-double" result
    };
    

    and it can be ran using:

    user.functions.add_tiktok_to_category([AnyBSON(stringLiteral: tiktoks.category), AnyBSON(stringLiteral: $0!)])
    

    Here's the documentation on running a MongoDB function in Swift: https://docs.mongodb.com/realm/ios/call-a-function/