Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
sharanan opened this issue Jul 30, 2018 · 23 comments
Assignees

Comments

@sharanan
Copy link

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);
});
});
}

@google-oss-bot
Copy link

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

@google-oss-bot
Copy link

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

@schmidt-sebastian
Copy link
Contributor

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

@sharanan
Copy link
Author

sharanan commented Jul 31, 2018

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

Using "uuid": "^3.3.2"

@schmidt-sebastian
Copy link
Contributor

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.

@loloDawit
Copy link

loloDawit commented Aug 11, 2018

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); }) })

@schmidt-sebastian
Copy link
Contributor

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

doc("postId").get()

instead of

doc("postId".get()

@loloDawit
Copy link

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); 
})

})
`

@loloDawit
Copy link

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)

@FlavioMarquesInf
Copy link

FlavioMarquesInf commented Feb 1, 2019

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.

@jbiddulph
Copy link

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?

@jbiddulph
Copy link

any fix for this yet?

@karthigb
Copy link

Same issue

@smashah
Copy link

smashah commented Mar 31, 2019

To those still having this issue try:

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

or use ${id} surrounded with backtics `

@baristaGeek
Copy link

@smashah thanks. This is the most straightforward solution

@kamlesh-nb
Copy link

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

@jpelton-stroud
Copy link

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 }

@smashah
Copy link

smashah commented Aug 17, 2019

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)))

@jpelton-stroud
Copy link

jpelton-stroud commented Aug 20, 2019 via email

@pradeepgill007
Copy link

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

@kierandesmond
Copy link

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

@laurenzlong
Copy link

@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.

@GzhiYi
Copy link

GzhiYi commented Jun 24, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests