How to use the firestore function from firebase-admin

Find comprehensive JavaScript firebase-admin.firestore code examples handpicked from public code repositorys.

firebase-admin.firestore is a module in the Firebase Admin SDK for Node.js that provides APIs for interacting with Firestore, a flexible and scalable NoSQL document database offered as part of the Firebase platform.

48
49
50
51
52
53
54
55
56
57
58
if (useFirestore) {
  admin.initializeApp(functions.config().firebase);
} else {
  console.log('No FIREBASE_CONFIG defined');
}
const firestore = useFirestore ? admin.firestore() : null;


const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});
fork icon33
star icon33
watch icon10

+ 4 other calls in file

-4
fork icon1
star icon2
watch icon1

+ 8 other calls in file

How does firebase-admin.firestore work?

firebase-admin.firestore is a module in the Firebase Admin SDK for Node.js that provides a client for interacting with Cloud Firestore, a flexible and scalable NoSQL document database offered by Firebase. It allows users to perform CRUD (create, read, update, delete) operations on documents and collections within Firestore, and also provides functionality for querying data, listening to real-time updates, and managing security rules.

182
183
184
185
186
187
188
189
190
191
  opponentActive = false;
}
//delete chat
if (opponentActive == false) {
  //updating user ratings 
  const chatsDocRef = admin.firestore().collection("chats").doc(topic).collection("chats").doc(chatID);
  const chatSnap = await chatsDocRef.get();
  const chat = chatSnap.data();
  await updateReputation(chat.nay, chat.yayReview);
  await updateReputation(chat.yay, chat.nayReview);
fork icon1
star icon2
watch icon1

+ 7 other calls in file

181
182
183
184
185
186
187
188
189
190
const userID = context.auth.uid;
const friendID = data.id;

if (typeof context.auth !== 'undefined') {
  return db.collection("UserData").doc(`${userID}`).update({
    listeningTo: admin.firestore.FieldValue.arrayRemove(friendID)
  }).then(() => {
    return db.collection("UserData").doc(`${friendID}`).update({
      listeners: admin.firestore.FieldValue.arrayRemove(userID),
      listenerCount: admin.firestore.FieldValue.increment(-1) //decrement
fork icon1
star icon1
watch icon1

+ 34 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const admin = require("firebase-admin");

// initialize Firebase Admin SDK
admin.initializeApp();

// get a Firestore reference
const db = admin.firestore();

// create a new document in a collection
const collectionRef = db.collection("users");
const newDocRef = collectionRef.doc(); // generates a new random document ID
newDocRef
  .set({
    name: "John",
    age: 30,
    email: "john@example.com",
  })
  .then(() => {
    console.log("Document created successfully!");
  })
  .catch((error) => {
    console.error("Error creating document:", error);
  });

This code initializes the Firebase Admin SDK, gets a reference to the Firestore database, creates a new document reference in a collection called "users", sets some data for the document, and logs a message when the document is successfully created or if there's an error.

6
7
8
9
10
11
12
13
14
15

verifyMessage:async(messageId,messageData)=>{

  const user=messageData.user
  const now=Date.now()
  var batch = admin.firestore().batch()

  try{

    const appSettingsCosts=await admin.firestore().doc('appSettings/costs').get()
fork icon1
star icon0
watch icon2

+ 149 other calls in file

129
130
131
132
133
134
135
136
137
138
139


/**
 * Cloud function that creates a new document for a user in the users collection when a user signs up
 */
exports.createUserDoc = functions.auth.user().onCreate((user) => {
  const userDoc = admin.firestore().collection('users').doc(user.uid);
  return userDoc.set({
    email: user.email,
    isAdmin: false
  });
fork icon0
star icon3
watch icon0

+ 14 other calls in file

38
39
40
41
42
43
44
45
46
47
const locationData = { locOrigin, locDestination }; // create separate object with location value
console.log("locationData: " + locationData + " timestamp: " + currentTime);
console.log("data: " + data);
if (typeof context.auth === 'undefined') {
    // request is made from an anonymous user
    return admin.firestore().collection('locations').add({ data, loc: locationData, time: currentTime }).then(() => {
        return "Data saved in Firestore";
    });
}
else {
fork icon0
star icon2
watch icon1

+ 13 other calls in file

95
96
97
98
99
100
101
102
103
104
105
});


exports.updatecomment = functions.https.onRequest((request, response) => {
    cors(request, response, () => {
        console.log("This is the body" + request.body.data);
        return admin.firestore().collection('comments').doc(request.query.id).update(request.body.data.comment).then(() => {
                response.json({data: "Updated document in database"});
            });
    });
});
fork icon0
star icon2
watch icon1

+ 8 other calls in file

78
79
80
81
82
83
84
85
86
87
}
if (nlp.age65to80) {
  openaiUser2 += "\nmale. employed. age:65 to 80\nfemale. employed. age:65 to 80";
}

return admin.firestore().collection("nlps").where("request", "==", openaiUser2).where("successful", "==", true).get().then((matchSnap) => {
  if (matchSnap.empty) {
    console.log("Request not in cache, calling OpenAI ChatCompletion API for Content Rewriting");
    return openai.createChatCompletion({
      model: "gpt-3.5-turbo",
fork icon0
star icon0
watch icon1

+ 139 other calls in file

17
18
19
20
21
22
23
24
25
26

// init
const uid = context.auth.uid;
const stance = data.stance;
const topic = data.topic;
const chatsCollection = admin.firestore().collection("chats");
const chatsSnap = await chatsCollection
  .where('topic', '==', topic)
  .where(stance, "==", 'null')
  .orderBy('time')
fork icon0
star icon0
watch icon1

+ 29 other calls in file

15
16
17
18
19
20
21
22
23
24
25
26
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-8rjxw%40hacktank-5277b.iam.gserviceaccount.com"
  })
});


const db = firebase.firestore();


const components = ["Navbar", "Button", "CheckboxComponent", "Box", "Image"];
const pages = ["index"];
const type = (filename) => {
fork icon0
star icon0
watch icon1

+ 4 other calls in file

29
30
31
32
33
34
35
36
37
38
39
40
const Transactions = db.collection('Transactions');
const Users = db.collection('Users');


// Initialize timestamps
const CurrentTime = admin.firestore.FieldValue.serverTimestamp();
const FutureTime = admin.firestore.Timestamp.fromMillis(Date.now() + 604800000);


module.exports = {
  Items,
  Reservations,
fork icon0
star icon0
watch icon1

+ 29 other calls in file

254
255
256
257
258
259
260
261
262
263
const dayArr = [];
for (let i = 0; i < 6; i++) {
  dayArr.push(moment().add(i+1, 'days').format("YYYY-MM-DD"));
}
const [locationDocumentSnapshot, forecastDocumentSnapshot] = await Promise.all([
  admin.firestore().collection('locations').doc(stationName).get(),
  admin.firestore().collection('forecast').doc('forecast').get()
]);
const locationDatas = locationDocumentSnapshot.data();
const forecastDatas = forecastDocumentSnapshot.data();
fork icon0
star icon0
watch icon0

+ 2 other calls in file

159
160
161
162
163
164
165
166
167
168
    courseId: courseId,
    name: courseName
  }

  await enrollmentsRef.update(
    { courses: admin.firestore.FieldValue.arrayUnion(enrollmentData) }
  );

} catch (error) {
  console.log("Error updating enrollment document:", error);
fork icon0
star icon0
watch icon0

1
2
3
4
5
6
7
8
9
10
11


class BusinessProfileController {
  async createProfile(req, res) {
    const { userId, email, name, photoUrl } = req.body;
    try {
      const newUserRef = admin.firestore().collection("businesses").doc(userId);
      await newUserRef.set({
        userId,
        email,
        name,
fork icon0
star icon0
watch icon0

46
47
48
49
50
51
52
53
54
55
56
});


// delete the doc in users/[uid] when user account deleted
exports.deleteUserDoc = functions.auth.user().onDelete(async (user) => {
  try {
    await admin.firestore().collection("users").doc(user.uid).delete();
    functions.logger.log("User doc " + user.email + " deleted successfully");
    return { result: "OK" };
  } catch (error) {
    functions.logger.error(
fork icon0
star icon0
watch icon0

58
59
60
61
62
63
64
65
66
67
68
69
70


exports.nuevoReporteUsuario = functions.firestore.document('/reportesUsuarios/{reporteUsuario}'
).onUpdate((snapshot, context) => {
    var listaTokens = [];


    admin.firestore().collection('usuarios').where('gudtech', '==', 'true').get().then((snapshot) => {
        var listaUsuarios = snapshot.docs;
        for (var usuario of listaUsuarios) {



fork icon0
star icon0
watch icon1

+ 26 other calls in file

28
29
30
31
32
33
34
35
36
37
38
39
40
41
// };


// // Initialize Firebase
//fs.initializeApp(firebaseConfig);


// const db = fs.firestore();


// admin query


// const datafetch = async () => {
fork icon0
star icon0
watch icon1

+ 4 other calls in file

72
73
74
75
76
77
78
79
80
81

// Enter geo value
if(typeof geoArray !== 'undefined') {
  geoArray.map(geo => {
    if(data.hasOwnProperty(geo)) {        
      data[geo] = new admin.firestore.GeoPoint(data[geo]._latitude, data[geo]._longitude);        
    } else {
      console.log('Please check your geo parameters!!!', geoArray);
      parameterValid = false;
    }
fork icon0
star icon0
watch icon0

+ 9 other calls in file