codemon
codemon

Reputation: 1594

How to find out if a record exists in Firestore (node)

Something that was so easy in firebase database, impossible for me to accomplish in firestore. I just need to know if a record exists in a specified document.

const user = firebase.auth().currentUser.uid;
const currentPostId = this.posts[index].id;
const ref = db.collection(`likes`).doc(`${currentPostId}`); // need to know if this doc has records

The post has a store of records with just the userids that have liked the post, and a timestamp.

enter image description here

So far I'm able to do this:

const ref = db.collection(`likes`).doc(`${currentPostId}`);

  ref
    .get()
    .then(snapshot => {
      console.log("Exists?" + snapshot.exists); //true
    })

But for the life of me I just CANNOT find a way to go one level deeper.

const ref = db.collection(`likes`).doc(`${currentPostId}/${user}`); //invalid reference segments must be odd numbers

const ref = db.collection(`likes`).doc(currentPostId).collection(user) //undefined

I've spent tthree days trying different ways. in firebase database it was just:

var ref = firebase.database().ref("users/ada");
ref.once("value")
  .then(function(snapshot) {
    var a = snapshot.exists();  // true
    var b = snapshot.child("name").exists(); // true
    var c = snapshot.child("name/first").exists(); // true
    var d = snapshot.child("name/middle").exists(); // false
  });

Upvotes: 1

Views: 4354

Answers (1)

Sean Stayns
Sean Stayns

Reputation: 4234

You can read the document and check whether the document has a field with the user id.

const ref = db.collection(`likes`).doc(currentPostId);

ref
.get()
.then(doc => {
  console.log("Exists?" + doc.exists); //true
  if(doc.exists){
     var documentData = doc.data();
     // Check whether documentData contains the user id 
     if (documentData.hasOwnProperty(userId)) {
        // do something
     }
  }
})

The code above is not tested but it should work.

A hint! You can and should store timestamps, which are generated on the client side with the firestore server timestamp:

admin.firestore.FieldValue.serverTimestamp();

Because, if the client have changed the local time you could get a wrong time.

Upvotes: 2

Related Questions