Let me try to explain the situation:
- To create an new document in firestore, I'm using
addmethod fromcollection - To keep type safe, using typescript, I'm using
withConverter - When I'm creating an new document, I don't have ID property on my object
- After the object is created, I have the ID property
bdw.. I'm using Mobx-state-tree
The code
Let me describe step by step
Company model defined by mobx-state-tree
const CompanyModel = types.model({
id: types.identifier,
name: types.string
});
Types that I will needed
After I call add method, CompanyReference is that what I get from firestore
type CompanyReference = firebase.firestore.DocumentReference<
Instance<typeof CompanyModel>
>;
TCompanySnapshot is that what I'm sending to the firestore by using add method
type TCompanySnapshot = Omit<SnapshotIn<typeof CompanyModel>, "id">;
Converting from and to firestore by using withCOnverter
- Send data to firestore, just user the regular
TCompanySnapshotobject - Receive some object from firestore (now I have the ID property), convert into
CompanyModel
const createCompanyConverter: firebase.firestore.FirestoreDataConverter<Instance<
typeof CompanyModel
>> = {
toFirestore(modelObject: TCompanySnapshot): firebase.firestore.DocumentData {
return modelObject;
},
fromFirestore(
snapshot: firebase.firestore.QueryDocumentSnapshot<TCompanySnapshot>,
options: firebase.firestore.SnapshotOptions
): Instance<typeof CompanyModel> {
const data = snapshot.data(options);
return CompanyModel.create({
id: snapshot.id,
...data
});
}
};
The problem
Now, when I tried to create method that create new company, I'm getting typing error
function addCompany(
// companyData: SnapshotIn<typeof CompanyModel>,
companyData: TCompanySnapshot
): Promise<CompanyReference> {
const added = firestore
.collection("companies")
// .withConverter<Instance<typeof CompanyModel>>(createCompanyConverter)
.withConverter<TCompanySnapshot>(createCompanyConverter)
.add(companyData);
return added; // <<<<<------ ERROR HERE
}
Property 'id' is missing in type
You can check this error on code sandbox
https://codesandbox.io/s/firebase-typescript-mobx-state-tree-n9s7o?file=/src/index.ts