Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

typescript - How do I write the document's ID into the document itself using Cloud Functions?

When a new user is created, I want to have a cloud function insert a new record into my users collection. I tried doing so with the code below but when I checked my logs it gave this error:

TypeError: Cannot read property 'resourcePath' of undefined at doc (/workspace/node_modules...)

The reason I want to do it this way is because I want to be able to store the document ID within the document itself. This will serve as a "rowpointer" like in SQL - a unique way to identify the row in the collection.

Code:

exports.newUserSignup = functions.auth.user().onCreate(user => {
  console.log('user created', user.email, user.uid);
  const doc = admin.firestore().collection('users').doc
  return doc(user.uid).set({
    createDate: admin.database.ServerValue.TIMESTAMP,
    modifiedDate: admin.database.ServerValue.TIMESTAMP,
    username: 'blah',
    email: user.email,    
    stat: 1,
    uid: user.uid,
    rowpointer: doc().id,
  });
});
question from:https://stackoverflow.com/questions/65864758/how-do-i-write-the-documents-id-into-the-document-itself-using-cloud-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're almost there, but have a few syntax errors in your code. This should be closer:

exports.newUserSignup = functions.auth.user().onCreate(user => {
  console.log('user created', user.email, user.uid);
  const doc = admin.firestore().collection('users').doc();
  return doc.set({
    createDate: admin.database.ServerValue.TIMESTAMP,
    modifiedDate: admin.database.ServerValue.TIMESTAMP,
    username: 'blah',
    email: user.email,    
    stat: 1,
    uid: user.uid,
    rowpointer: doc.id,
  });
});

I highly recommend keeping the reference docs handy when you're having trouble with this type of exercise, as I found the problem pretty quickly when looking at CollectionReference.doc() and DocumentReference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...