samuelgozi/firebase-firestore-lite

ref.set promise returning undefined when creating document

Closed this issue · 5 comments

This may be a me issue, I'm still a bit of a JS novice. I'm trying to create some default fields whenever a document is created, specifically {id: ..., configs: []}. However, the problem is that when the document ref does not exist, the ref.set promise returns undefined. However, even though it returns undefined, the data is properly updated as I would expect within firebase. If I run the exact same script over again, after the data is properly updated and it has errored once, everything works as expected (since it is skipping the .catch block?).

Any help appreciated.

  const userRef = db.ref(`users/${user}`);

  /* eslint-disable no-unused-vars */
  const res = userRef
    .get()
    .then((r) => {
      // User is found!
      return r;
    })
    .catch((e) => {
      // User not found. Creating
      return userRef.set({ // <--- returns undefined?
        id: user,
        configs: [],
      });
    })
    .then((r) => {
      console.log(r, typeof r); // <----- undefined "undefined"
      // Append new object to configs
      const newConfigs = r.configs; // Errors since r is undefined
      newConfigs.push({ name, url, query });
      return userRef.update({
        configs: newConfigs,
      });
    })
    .then((r) => {
      console.log("updated state: ", r);
    });

Issue-Label Bot is automatically applying the label bug to this issue, with a confidence of 0.64. Please mark this comment with 👍 or 👎 to give our bot feedback!

Links: app homepage, dashboard and code for this bot.

Hi, and thanks for opening an issue!
If I understand you correctly, you are expecting "ref.set()" to return the data?

In earlier versions of the lib, it used to work that way, but later it was changed because it restricted the use of Transforms and added much complexity to the code.

So ref.set() along with the rest of the mutating methods currently don't return the resulting data from the database, instead it returns a promise that resolves once the data was successfully mutated.

Please let me know if this answers your question.

I expect it to return a promise, however it seems the promise is resolving to undefined if and only if ref does not exist yet.

Well, just tested it again, and it returns a promise every time. When the document exists and when it doesn't.

const userRef = db.ref(`public/setTest`);

userRef
  .set({
    id: "123",
    configs: [],
  })
  .then(console.log);

The issue is that in your code the catch block is not called when the document exists, so the second then block gets the value from the first then that is called from the get() call.

change the set by add

`// Add a new document with a generated id.

const res = await db.collection('cities').add({
name: 'Tokyo',
country: 'Japan'
});

console.log('Added document with ID: ', res.id);`