Home > Mobile >  TypeError: listingsRef.add is not a function. (In 'listingsRef.add(updatedUploadObjects)',
TypeError: listingsRef.add is not a function. (In 'listingsRef.add(updatedUploadObjects)',

Time:12-19

I'm developing a listing app, and using firebase as my back end, before I add .orderBy statement to sort the data by creating date, everyting works fine and I can update new post on the app, but after I add .orderBy('createdAt', 'desc') in the listing, I can not update any new post and there is a error "TypeError: listingsRef.add is not a function. (In 'listingsRef.add(updatedUploadObjects)', 'listingsRef.add' is undefined) the code is shown below:

    import { setFavoriteItems } from '../../../favorites/redux'
import { firebase } from '../../../api/firebase/config'
import ServerConfiguration from '../../../../ServerConfiguration'

const savedListingsRef = firebase
  .firestore()
  .collection(ServerConfiguration.database.collection.SAVED_LISTINGS)
  .orderBy('createdAt', 'desc')
const listingsRef = firebase
  .firestore()
  .collection(ServerConfiguration.database.collection.LISTINGS)
  .orderBy('createdAt','desc')
const ListingCategoriesRef = firebase
  .firestore()
  .collection(ServerConfiguration.database.collection.CATEGORIES)
  .orderBy('order')

and this:

 if (selectedItem) {
    listingsRef
      .doc(selectedItem.id)
      .update({ ...updatedUploadObjects, photo: coverPhoto })
      .then(docRef => {
        callback({ success: true })
      })
      .catch(error => {
        console.log(error)
        callback({ success: false })
      })
  } else {
    listingsRef
      .add(updatedUploadObjects)
      .then(docRef => {
        if (docRef.id) {
          listingsRef
            .doc(docRef.id)
            .update({ id: docRef.id, photo: coverPhoto })
        }
        callback({ success: true })
      })
      .catch(error => {
        console.log(error)
        callback({ success: false })
      })
  }
}

CodePudding user response:

This defines a CollectionReference:

const savedListingsRef = firebase
  .firestore()
  .collection(ServerConfiguration.database.collection.SAVED_LISTINGS)

If you check that link, you'll see that a CollectionReference has an add method, meaning that you can add a document to it.


This defines a Query:

const savedListingsRef = firebase
  .firestore()
  .collection(ServerConfiguration.database.collection.SAVED_LISTINGS)
  .orderBy('createdAt', 'desc')

If you check that last link, you'll see that a query doesn't have an add method, so you can't add something to a query.


You'll want to keep the CollectionReference around too, so that you can call add() on that.

  • Related