Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FieldValue undefined when using functions and Firestore

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.

like image 869
Chris Avatar asked Nov 03 '17 09:11

Chris


3 Answers

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.

like image 103
Chris Avatar answered Nov 12 '22 09:11

Chris


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

like image 14
Abhin Krishna KA Avatar answered Nov 12 '22 10:11

Abhin Krishna KA


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

like image 5
0xPixelfrost Avatar answered Nov 12 '22 10:11

0xPixelfrost