49

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
  • 7,830
  • 6
  • 38
  • 72

3 Answers3

89

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
  • 7,830
  • 6
  • 38
  • 72
  • 5
    I wasted so much time on this. Thanks for sharing! – Julien L Nov 07 '17 at 23:06
  • 2
    Oh man I wish I found this answer sooner. Thanks for saving me. – stevejboyer Nov 17 '17 at 07:49
  • 8
    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
14

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
  • 732,580
  • 175
  • 1,330
  • 1,459
Abhin Krishna KA
  • 745
  • 8
  • 13
10

Here you can find the solution on github.

Using typescript with

"firebase-admin": "^11.0.0"
"firebase-functions": "^3.22.0"

you have to use

import { FieldValue } from 'firebase-admin/firestore'

Same for TimeStamp

0xPixelfrost
  • 10,244
  • 5
  • 39
  • 58