How to create a reference field in a document from Dart code – Flutter Firebase?

In Cloud Firestore you can create documents with different types of fields, one of them is the Reference field.
I want to create a Reference field from Dart code, but it always creates it as a string.

I have a collection called "usuarios" (users) and I want to create a subcollection inside that collection called "categoriasFavoritas" (favourite cathegories), where there are listed the favourites cathegories of the user.
I have this code:

    CollectionReference<Object?> referenciaCategoriasFavoritas = bbdd.collection('/usuarios/${docUsuario.id}/categoriasFavoritas');

    listaCategoriasFavoritas.forEach((idCategoria) {
      var docCategoriaFavorita = referenciaCategoriasFavoritas.doc();
      var ref = bbdd.collection('categorias').doc();
      var jsonCategoriaFavorita = {'idCategoria': ref.path}; //Here
      docCategoriaFavorita.set(jsonCategoriaFavorita);

I create the subcollection "referenciaCategoriasFavoritas" inside the user document and, as I have the list of the favourite cathegories ids (listaCategoriasFavoritas), I just want to put those ids as a reference of the "categorias" (cathegories) collection in the subcollection I’ve created.
The part when I put the //Here comment es where I create that reference field.

I’ve tried this option too, but it doesn’t work neither:

    var jsonCategoriaFavorita = {'idCategoria': '/categorias/$idCategoria'};

It’s saved as a string field, and not as a Reference field, as you can create directly in Cloud Firestore:

Field created as a string

Does anyone know how to create reference fields from the code?

>Solution :

As Renaud commented, you need to set a DocumentReference object as the value of the field. The database will then store that reference, and display its path in the Firebase console.

So:

var jsonCategoriaFavorita = {'idCategoria': ref};

Leave a Reply