javascriptrealmmongodb-realm

Realm Delete an Object in One to Many relationship


I have a ONE TO MANY schema like this:

SHOP SCHEMA

const Shop = {

  name: "Shop",

  properties: {

      _id: "objectId",
      products:"Products[]"
 }
}

PRODUCTS SCHEMA

const Products = {

  name: "Products",

  properties: {

      _id: "objectId",
      name : "string",
    }
}

A shop has many products and as it can be seen 'pictorially' below

_id:'60f73ca7c1a70278596cc7d0',
products:[
      {_id:1, name:'product1'},
      {_id:2, name: 'product2'},
      {_id:3, name: 'product3'}
]

Now, say I want to delete product2, How do I do it with mongodb realm?

What I have tried so far

const obj = realm.objects('Shop').filtered("_id == $0 AND products._id == $1", ObjectId('60f73ca7c1a70278596cc7d0'), ObjectId('2'))
realm.write(() => {
   realm.delete(obj)
})

But this doesn't delete the item in the products array.

How can I achieve deleting a specific element in products array in this One to Many relationshiop using realm?


Solution

  • The code in the question is very close to being correct, you just need to filter for the product you want to delete instead of the shop. It's not clear if you know the product _id or name but you can filter by either one.

    Here's the code to filter for products with an _id of 1 and then delete it (which will also remove it from any lists that contain a reference to it.

    const prod = realm.objects('Products').filtered("_id == 1");
    realm.write(() => {
       realm.delete(prod);
       prod == null;
    })
    

    The above is taken from the documentation Filter Query and Delete An Object

    Keep in mind this will delete all products with id = 1 so as long as _id's are unique it's fine.