Firebase-admin-node: All firestore set(doc) calls fail due to "Error:Argument "documentPath" is not a valid ResourcePath. Path must be a non-empty string"

Created on 30 Jul 2018  Â·  23Comments  Â·  Source: firebase/firebase-admin-node

Environment

  • Operating System version: macOS High Siera (10.13.3)
  • Firebase Admin Node SDK version: 5.12.1
  • Firebase Functions version: 1.0.3
  • Firebase Product: Firestore, Functions

Problem

While creating a new document/collection in firestore using firebase admin node sdk, within a cloud function, all requests fail with following error:-

Argument "documentPath" is not a valid ResourcePath. Path must be a non-empty string.
at Object.exports.(anonymous function) [as isResourcePath] (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/validate.js:86:15)
at CollectionReference.doc (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/src/reference.js:2113:16)
at Promise (/user_code/lib/api.js:10:37)
at Object.exports.createNewClient (/user_code/lib/api.js:8:12)
at Object. (/user_code/lib/index.js:55:33)
at next (native)
at /user_code/lib/index.js:7:71
at __awaiter (/user_code/lib/index.js:3:12)
at Request.request [as _callback] (/user_code/lib/index.js:47:70)
at Request.self.callback (/user_code/node_modules/request/request.js:185:22)

Steps to reproduce:

Try creating a new doc using firestore -> collection.doc(doc.id).set(doc)

Relevant Code:

My application code that's failing (this was working a few minutes ago and started failing without any changes):-
export const createNewClient = (client) => {
return new Promise((resolve, reject) => {
store.collection("clients").doc(client.id).set(client).then(docRef => {
resolve(client);
}, error => {
reject(error);
});
});
}

firestore

Most helpful comment

To those still having this issue try:

admin.firestore().collection('whatever').doc(""+id);

or use ${id} surrounded with backtics `

All 23 comments

Hey there! I couldn't figure out what this issue is about, so I've labeled it for a human to triage. Hang tight.

Hmmm this issue does not seem to follow the issue template. Make sure you provide all the required information.

Can you let us know what client.id is? That would help me determine what is going on here.

Its a hashcode generated with uuid/v4.
Here's a sample:- 7d266f05-f476-4e0e-b11f-ad48e39952b8

Using "uuid": "^3.3.2"

The error that is thrown from this statement:

if (!is.string(resourcePath) || resourcePath === '') {
      throw new Error(`Path must be a non-empty string.`);
    }

This all happens in path.js. I would suspect that the value you see here is not actually a string at the point where we are checking.

having the same issue
Error: Argument "documentPath" is not a valid ResourcePath. Path must be a non-empty string.
at Object.exports.(anonymous function) [as isResourcePath] (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/validate.js:89:23)
at CollectionReference.doc (/user_code/node_modules/firebase-admin/node_modules/@google-cloud/firestore/build/src/reference.js:1813:22)
at exports.updateLikeCount.functions.https.onRequest (/user_code/lib/index.js:14:43)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/providers/https.js:57:9)
at /var/tmp/worker/worker.js:686:7
at /var/tmp/worker/worker.js:670:9
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

code snippet
export const update = functions.https.onRequest((req, res)=>{ //...some code //...some code admin.firestore().collection("updates").doc("postId".get().then((data)=>{ //....some code //...some code admin.firestore().collection("updates").doc("postId".update(data).then(()=>{ res.status(200).send("Done") }).catch((err)=>{ res.status.(err.code).send(err.message); }) }).catch((err)=>{ res.status.(err.code).send(err.message); }) })

@loloDawit Note that your code is missing parenthesis. It should be

doc("postId").get()

instead of

doc("postId".get()

that a typo here is the exact code

admin.firestore().collection("posts").doc(postId).get().then((data)=>{
    console.log(data);
    let likeCount = data.data().likeCount || 0; // if like doesn't exists pass 0
    let like = data.data().like || [];

    let updateData = {}; 

    if(action == "like"){
        updateData["likeCount"] = ++likeCount; 
        updateData[`like.${userId}`] = true; 
    }else{
        updateData["likeCount"] = --likeCount; 
        updateData[`like.${userId}`] = false; 
    }

    admin.firestore().collection("posts").doc(postId).update(updateData).then(()=>{
        response.status(200).send("Done")
    }).catch((err)=>{
        response.status(err.code).send(err.message);
    })
}).catch((err)=>{
    response.status(err.code).send(err.message); 
})

})
`

I've figured out the issue. the issue is not related to firebase. It's the way I was testing my code using the postman app. The raw data needs to be in JSON format. By default is set to text, it must be changed to JSON(application/json)

that a typo here is the exact code

admin.firestore().collection("posts").doc(postId).get().then((data)=>{
    console.log(data);
    let likeCount = data.data().likeCount || 0; // if like doesn't exists pass 0
    let like = data.data().like || [];

    let updateData = {}; 

    if(action == "like"){
        updateData["likeCount"] = ++likeCount; 
        updateData[`like.${userId}`] = true; 
    }else{
        updateData["likeCount"] = --likeCount; 
        updateData[`like.${userId}`] = false; 
    }

    admin.firestore().collection("posts").doc(postId).update(updateData).then(()=>{
        response.status(200).send("Done")
    }).catch((err)=>{
        response.status(err.code).send(err.message);
    })
}).catch((err)=>{
    response.status(err.code).send(err.message); 
})

})
`

this is from Feedly app cource, a change the like function and works:

like(post) {
const body = {
postId: post.id,
userId: firebase.auth().currentUser.uid,
action: post.data().likes && post.data().likes[firebase.auth().currentUser.uid] === true ? 'unlike' : 'like'
};

console.log(body);

const headers = new HttpHeaders()
  .set('Access-Control-Allow-Origin', '*')
  .set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT')
  .set('Content-Type', 'application/json')
  .set('Accept', 'application/json');

// OBS: o (responseType: 'text') impede que a resposta seja parseada como json,
// evitando erro, pois nesse caso a resposta é uma string apenas e não um objeto json.
const url = 'https://us-central1-feedly-xxxx.cloudfunctions.net/updateLikesCount';
this.http.post(url, body, {
  headers: headers,
  responseType: 'text',
}).subscribe(data => {
  console.log(data);
}, error => {
  console.log(error);
});

}

where is: "JSON.stringify(body)" I remove JSON.stringify() and left only "body" variable.

I'm having this issue too, I am leaving JSON.Stringify in as that needs to be in there... Did you find a fix for it?

any fix for this yet?

Same issue

To those still having this issue try:

admin.firestore().collection('whatever').doc(""+id);

or use ${id} surrounded with backtics `

@smashah thanks. This is the most straightforward solution

To those still having this issue try:

admin.firestore().collection('whatever').doc(""+id);

or use ${id} surrounded with backtics `

both these not working for me

just ran into this in my own project, discovered that the data I was grabbing did, in fact, have an object with an empty key:
{ items: { '': [Object], A: [Object], B: [Object], C: [Object] }, size: 4 }

If you have issues with empty properties then please try stringifying the object then immediately parsing it then sending it to Firestore.

E.g

.....update(JSON.parse(JSON.stringify(objectToSend)))

Awesome, I'll give it a shot; thanks for the heads up!

On Sat, Aug 17, 2019, 8:20 AM S.M.A.Sh notifications@github.com wrote:

If you have issues with empty properties then please try stringifying the
object then immediately parsing it then sending it to Firestore.

E.g

.....update(JSON.parse(JSON.stringify(objectToSend)))

—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/firebase/firebase-admin-node/issues/320?email_source=notifications&email_token=AJ3IAAGVX2LIA5U4BAB75KTQE7UJDA5CNFSM4FMZHXK2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD4QKCNI#issuecomment-522232117,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AJ3IAAENIGUEFP4VPHNWU3DQE7UJDANCNFSM4FMZHXKQ
.

The document id you are passing as a reference is not matching with document id in the Firestore in case of an updation.

Hi All,

I have this issue only with a trigger / onCreate -
To me it looks like standard trigger code. Compared it to the docs and still no joy. Any ideas?

`
exports.onIntroductionAdded = functions
.region("europe-west1")
.firestore.document('introductions/{introductionId}')
.onCreate(async (snapshot) => {
// const batch = db.batch();
try {

}
catch(e){

}
}`

Thank you,
Kieran

@kierandesmond If you are able to deploy the function, then the code you provided is not what's causing the issue, it's probably another line of code inside your function.

I've figured out the issue. the issue is not related to firebase. It's the way I was testing my code using the postman app. The raw data needs to be in JSON format. By default is set to text, it must be changed to JSON(application/json)

That is right.Set body to "JSON" will solve this issue.
image

Was this page helpful?
0 / 5 - 0 ratings