Home > Mobile >  add a document which contains fields of type integers to firestore
add a document which contains fields of type integers to firestore

Time:12-09

Whenever I add a new document to the database its fields by default take the type of string even when I add a number (I'm using React.js)

  const [age, setAge] = useState(0);
<input
     type="number"
     className="loginOrSignupPopup__age"
     placeholder="Age"
     value={age}
     onChange={(e) => {
         setAge(e.target.value);
         console.log(typeof e.target.value); // string
     }}
 />
async function createUser() {
    await addDoc(usersCollectionRef, { name: name, age: age });
    console.log(typeof age); // string
  }

This is how the field is saved in the firestore database and I want it to be a number, not a string

enter image description here

CodePudding user response:

Answering this as Community wiki. As mentioned in the comments,

To save data as number in firestore database use Number() function.

Since you get this: console.log(typeof e.target.value); // string it really seems to be a string. You could try using parseInt to convert it to a number before passing it to the database.

You can also try {name, age: age}

  • Related