How do I insert with default values

I am writing a function to insert a large document with many attributes. I have defaults in my Swift Object Model. But in the function it errors out need values for all the non-optional fields. Do I have to set them all to value? Why doesn’t the model know what the default should be?

HI @James_Cicenia,

Just to check my understanding (correct me if I’ve misinterpreted)…

  • You have a Swift class that inherits from Object from the iOS Realm SDK
  • In that class, you initialize some non-optional attributes
  • You have a Realm Function where you’re creating a new document and inserting it into MongoDB Atlas
  • In that function, you’re not including those non-optional attributes, and you’re getting a validation error.

If that’s the case, then this is what I’d expect to see.

The schema in your backend app is used to validate a document before it’s written to Atlas – it’s a pass/fail and can’t modify the document to make it conform (e.g., by providing default values for missing fields). The schema has no knowledge that your Swift class initializes those fields.

If you’ve lots of functions that need to write to this collection, then you could create a wrapper Realm function that they call rather than writing to the database directly. That new function could then apply your default values.

Can you include your Realm model so we have a clear picture of how that’s set up?

your explanation was very helpful. Lot to learn here bootstrapping myself.