35

I have the following function:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const FieldValue = require('firebase-admin').FieldValue;

module.exports = functions.firestore
  .document('students/{studentId}')
  .onDelete(event => {
    const student = event.data.previous.data();
    const { id, semester } = student;
    const classId = student.class;
    const deleteObj = {};
    deleteObj[id] = FieldValue.delete(); //Line 12, this is where the error orccurs
    return admin
      .firestore()
      .collection('semesters')
      .doc(semester)
      .collection('students')
      .doc(classId)
      .update(deleteObj);
  });

Every time i run it I get the following error:

TypeError: Cannot read property 'delete' of undefined
    at module.exports.functions.firestore.document.onDelete.event (/user_code/deleteStudent.js:12:37)

Looking at the docs I cant really see what I am doing wrong?

// Get the `FieldValue` object
var FieldValue = require("firebase-admin").FieldValue;

// Create a document reference
var cityRef = db.collection('cities').doc('BJ');

// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
    capital: FieldValue.delete()
});

Update

So, using the web equivalent seems to work: admin.firestore.FieldValue.delete(). But that seems like a bug since i'm in a nodejs environment? Can any Firebaser confirm or deny wether that is the case or not? I'd gladly file a bug report.

Chris
  • 6,719
  • 5
  • 35
  • 63

2 Answers2

60

Turns out it was a mistake in the documentation, the correct import should have been const FieldValue = require('firebase-admin').firestore.FieldValue;

Update

It should be said that Firebase responded within hours and are correcting the docs asap.

Chris
  • 6,719
  • 5
  • 35
  • 63
  • 4
    I wasted so much time on this. Thanks for sharing! – Julien L Nov 07 '17 at 23:06
  • 1
    Oh man I wish I found this answer sooner. Thanks for saving me. – stevejboyer Nov 17 '17 at 07:49
  • 4
    Firestore is horribly documented. The only place the FieldValue import is documented is in a completely unrelated function's sample code at https://firebase.google.com/docs/firestore/manage-data/add-data#update_fields_in_nested_objects Need better documentation! – Ray Li Jun 03 '19 at 03:19
4

It worked!

Require firebase-admin

const admin = require('firebase-admin')

Add this constant

const fieldValue = admin.firestore.FieldValue; 

Now use

fieldValue.delete()

For more reference : otcollect.com/post

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388