How to create a unique Primary Key

Hello! I am refering another Document in one of my collections and for some reason when i try to add 2 in a row it says " Attempting to create an object of type ‘Developer’ with an existing primary key value ‘64c26d0bedcdf93ffacbcc1f’"

Shouldn’t this be automatically generated and unique? This is my Model.

import {BSON} from "realm";

export const Developer = {
    name: 'Developer',
    properties: {
        _id: {type: 'objectId', default: new BSON.ObjectId()},
        createdAt: {type: 'date', default: new Date()},
        founded: {type: 'date', default: new Date()},
        name: 'string?',
        website: 'string?',
        status: 'string?',
        image: 'string?',
        deleted: { type: 'bool', default: false},
        userId: 'string?',
    },
    primaryKey: '_id',
};

I thought this generates a new _id every single time. Also the weird thing is in my System Model, I am referencing a Developer and sometimes when making a new System it says I tried to create a new Developer with an existing primary key? here is my System Model.

import {BSON} from "realm";

export const System = {
    name: 'System',
    properties: {
        _id: {type: 'objectId', default: new BSON.ObjectId()},
        createdAt: {type: 'date', default: new Date()},
        releaseDate: {type: 'date', default: new Date()},
        name: 'string?',
        shortName: 'string?',
        generation: 'string?',
        website: 'string?',
        developer: 'Developer?',
        image: 'string?',
        userId: 'string?',
    },
    primaryKey: '_id',
};

what am I doing wrong? thank you. This is my realm.create code. I shouldn’t need to pass in _id as it should be created and unique each time?

realm.write(() => {
                return realm.create('System', {
                    name,
                    releaseDate,
                    shortName,
                    generation,
                    website,
                    developer,
                    image,
                    userId: userId ?? 'SYNC_DISABLED',
                });
            });

Hi @Mike_Powell,

That snippet is generating an ObjectId at process start and using that value as a static default value. What you’re looking for is a dynamic default value, which is available starting with v11.1.0: https://www.mongodb.com/docs/realm/sdk/react-native/model-data/define-a-realm-object-model/#set-a-default-property-value

Thank you for the reply, I am using 11.10.1.

This is the example code provided in the realmtest template. I had to change it when I made some destructive changes and for some reason it did not match up correctly. So did i break it? Will the below code generate a new ID each time? otherwise the code provided is wrong.

import Realm, {BSON} from 'realm';

// To use a class as a Realm object type in Typescript with the `@realm/babel-plugin` plugin,
// simply define the properties on the class with the correct type and the plugin will convert
// it to a Realm schema automatically.
export class Task extends Realm.Object {
  _id: BSON.ObjectId = new BSON.ObjectId();
  description!: string;
  note!: string;
  isComplete: boolean = false;
  createdAt: Date = new Date();
  userId!: string;

  static primaryKey = '_id';

SO it seems my real issue is that when I am creating a System, instead of using the developer I am passing in, it is attempting to create another developer with the same _id. Why? what is the correct way to link an existing developer?

The dogs only show how to set up the schema and now how to link the actual code?

Do I set the developer field to a string with the _id? do i just pass in the developer object?

I have tried numerous things.

return realm.create('System', {                    
                    developer: developer._id,
                });

return realm.create('System', {                    
                    developer: developer
                });

return realm.create('System', {                    
                    developer: {_id:developer._id}
                });

none of these work correctly and all try to make a new developer.

ok I have solved both my issues, one of which seems to be a typescript thing.

Seems I was passing in the type to the add function but I guess I need to tell it that it was also a Realm.Object. Not really but once I added that behaviour started to work as expected.

The docs really need to be updated to show examples of setting the reference. Because passing in an object to create the reference is not really clear why the create function would try to create a new one instead of using the current one.

Would love to see a non typescript version.

developer: Developer & Realm.Object,

instead of

developer: Developer,

as for the unique _id. once I added an arrow function it fixed the issue i think.
The example project needs to be checked to ensure it is correct, as I copied that.
Just happy to have solved it, thank you.

export const Developer = {
    name: 'Developer',
    properties: {
        _id: {type: 'objectId', default: () => new BSON.ObjectId()},
        createdAt: {type: 'date', default: new Date()},        
    },
    primaryKey: '_id',
};

Glad to hear you figured it out! Keep in mind you’ll want to use a factory function for your createdAt default value in that last snippet you shared as well.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.