such a document already exists что делать
I want to add data into the firestore database if the document ID doesn’t already exists. What I’ve tried so far:
The goal is to check all the documents ID in the database and see in any matches with the «varuId» variable. If it matches, the document won’t be created. If it doesn’t match, It should create a new document
4 Answers 4
You can use the get() method to get the Snapshot of the document and use the exists property on the snapshot to check whether the document exists or not.
Use the exists method on the snapshot:
getDocuments() fetches the documents for this query, you need to use that instead of document() which returns a DocumentReference with the provided path.
Edit: @Doug Stevenson is right, this method is costly, slow and probably eat up the battery because we’re fetching all the documents to check documentId. Maybe you can try this:
The reason I’m doing null check on the data is, even if you put random strings inside document() method, it returns a document reference with that id.
Firestore: How to check if document exists, and create one if it doesn’t #1272
Comments
avilao commented Oct 15, 2017
Is there a way to check if a document already exists in the database?
Couldn’t find an example.
The text was updated successfully, but these errors were encountered:
larssn commented Oct 16, 2017
Don’t think you can do it with AFS, and might have to rely on the underlying framework:
jamesdaniels commented Oct 16, 2017
As of 5.0 rc3 empty sets/docs should be handled correctly.
I am working on an API to make return or create easier.
ButhSitha commented Oct 17, 2017
@jamesdaniels I import the operator take already but i got error
i can’t use doc with take operator.
dhawken commented Oct 26, 2017 •
Might be incorrect usage of snapshotChanges(), but its able to determine if something is there. If you wanted to manually create it, I believe you could do that once you’ve determined it doesn’t exist.
sneurlax commented Nov 12, 2017
Just popping in to report that neither take() nor do() work (exist) for me on AngularFirestoreDocument
sneurlax commented Nov 12, 2017
Currently handling this by attempting an update and set ting on error as such:
vaurelios commented Dec 15, 2017 •
@jamesdaniels example is missing somethings:
Vicky443 commented Dec 17, 2017 •
const userRef: AngularFirestoreDocument = this.afs.doc( users/$
userRef.valueChanges().subscribe(res=> <
if(res) <
// do your perform
>
> );
buchmiller commented Feb 4, 2018
Here’s a variation of @sneurlax’s example:
Zufarsk8 commented Feb 5, 2018
@buchmiller
But by doing so, it will be a write in the document.
A write in the document is more costly in terms of pricing according to firebase pricing.
If we can read before we write it will be more cost efficient 🙂
olanRay94 commented Mar 26, 2018
How about searching 2 parameters, like username and email?
I am looking for username and email that I type in input.
I think it could be in 2 ways:
Maybe we can do all in one query in where clause using OR statement. I am not sure if firestore support it.
I think we can search the username first. If it return null, we continue search the email. I am looking for this possible way. Any suggestion?
math-a3k commented Apr 19, 2018
jwv commented May 21, 2018
miglrodri commented Aug 31, 2018 •
Vino16491 commented Aug 31, 2018
@mk4yukkalab do you got workaround to ur concern
And if i need a query like : this.afs.collection(‘users’, ref => ref.where(’email’, ‘==’, email)) how i can do that?
Hanan0o0 commented Sep 15, 2018
And if i need a query like : this.afs.collection(‘users’, ref => ref.where(’email’, ‘==’, email)) how i can do that?
Hanan0o0 commented Sep 15, 2018
@mk4yukkalab do you got workaround to ur concern
And if i need a query like : this.afs.collection(‘users’, ref => ref.where(’email’, ‘==’, email)) how i can do that?
hafizmowais commented Nov 12, 2018 •
This one should work
JeffGreat commented Nov 15, 2018
@mk4yukkalab @Hanan0o0 @Vino16491
in angular 6 I manage like that
funct7 commented Dec 16, 2018
Currently handling this by attempting an update and set ting on error as such:
xgenem commented Mar 27, 2019
@larssn solution still works as of date.
yuricamara commented May 21, 2019
@buchmiller
But by doing so, it will be a write in the document.
A write in the document is more costly in terms of pricing according to firebase pricing.
If we can read before we write it will be more cost efficient 🙂
Are you sure? For me it makes more sense, not be a cost in case of update. So, the cost will be the same as @sneurlax method.
vasiledoe commented Nov 6, 2019 •
For Android in Kotlin:
MikeC711 commented Jan 28, 2020
And if i need a query like : this.afs.collection(‘users’, ref => ref.where(’email’, ‘==’, email)) how i can do that?
I am not an expert so there may be better ways, but here is what I did in that situation:
this.afs.collection(‘eicpeople’, ref => ref.where(‘familyKey’, ‘==’, person.familyKey))
.valueChanges().pipe(take(1)).subscribe(matchingRecs => <
if (matchingRecs.length > 0) // this is my equivalent to exists
else // this is no match
jluz88 commented Jun 11, 2020 •
Maybe a bit late, but this worked for me for a web app.
kylebradshaw commented Jun 16, 2020 •
The way I went about this a combo of creating my own unique ID based on the data by using a sha library (js-sha256), just JSON.stringify(data) to get your id then follow the approach above.
Data is always overwritten.
Awais-mohammad commented Aug 12, 2020
Don’t think you can do it with AFS, and might have to rely on the underlying framework:
Awais-mohammad commented Aug 12, 2020
I am also trying to find a solution for angular 8
AbhiShrek commented Sep 14, 2020
davecoffin commented Sep 30, 2020
Thought Id share this. I am doing it like so:
surajsahani commented Mar 5, 2021
yes but in this case, the previous record of sam would override how to handle that?
surajsahani commented Mar 5, 2021
This one should work
but in this case previous recod would be override with the new one right? how can i check if previous was present don’t write new one. or on’t update new values
surajsahani commented Mar 5, 2021
Thought Id share this. I am doing it like so:
how to check if doc exist show an toast that doc exist and if not set the value?
smaity35 commented Jun 9, 2021
Am So happy It Working. Thank You
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Drupal Русскоязычное сообщество
Создал на Гитхабе репу.
Выдает
fatal: remote origin already exists.
Устанавливать Drupal можно так:
1.
Может проблема от того, что раньше пользовался 2-м способом, а теперь попробовал 1-м?
Комментарии
пробовал решить так (не получилось):
Вроде работает
правда папка files с картинками почему-то пошла в репу
Так зачем ты инициируешь репозиторий (git init), если у тебя уже есть удаленный репозиторий (https://github.com/Vasy0K/portal.git).
Прочитай какой-нибудь букварь по гиту, например вот этот: https://git-scm.com/book/ru/v2
Какие-то продвинутые вещи не нужны, хотя-бы просто понимание базовых команд, ветвей и работы с удаленной репой.
Видимо, как-то слишком по диагонали, раз возникают такие вопросы и удивления.
Пойми правильно, не стоит задача подколоть. Просто твой вопрос немедленно сигнализирует о том, что ты не понимаешь что за команды ты вводишь, что они делают и как работает распределенный гит. Инвестируй 2-3 часа времени на четкое понимание основ, этим ты застрахуешь себя и своих клиентов от седых волос и сидений в ночи в попытке восстановить похеренный репозитарий.
До того, как разбираться собственно с командами git, и пытаться методом тыка что-то сделать, неплохо бы понимать концептуально, как вообще строится процесс работы. Как вариант, почитать книжку по ссылке @Selpi.
Я понимаю, когда что-то делаю, а не читаю.
Проблема выше решена, но мне хотелось бы услышать технический комментарий, а не посыл.
Дак тебе объяснили уже, что если бы ты понимал, что делаешь, этого вопроса вообще бы не возникло
На развитие drupal.ru
Ваша финансовая помощь дает нам возможность оплачивать хостинг и поддерживать стабильную работу сайта. Благодарим за поддержку!
HTTP response code for POST when resource already exists
I’m building a server that allows clients to store objects. Those objects are fully constructed at client side, complete with object IDs that are permanent for the whole lifetime of the object.
I have defined the API so that clients can create or modify objects using PUT:
The
Now, I’m also considering allowing clients to create the object using POST:
Since POST is meant as «append» operation, I’m not sure what to do in case the object is already there. Should I treat the request as modification request or should I return some error code (which)?
17 Answers 17
My feeling is 409 Conflict is the most appropriate, however, seldom seen in the wild of course:
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can’t complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
According to RFC 7231, a 303 See Other MAY be used If the result of processing a POST would be equivalent to a representation of an existing resource.
The 422 Unprocessable Entity status code means the server understands the content type of the request entity (hence a 415 Unsupported Media Type status code is inappropriate), and the syntax of the request entity is correct (thus a 400 Bad Request status code is inappropriate) but was unable to process the contained instructions.
It’s all about context, and also who is responsible for handling duplicates in requests (server or client or both)
If server just point the duplicate, look at 4xx:
For implicit handling of duplicates, look at 2XX:
if the server is expected to return something, look at 3XX:
when the server is able to point the existing resource, it implies a redirection.
If the above is not enough, it’s always a good practice to prepare some error message in the body of the response.
Late to the game maybe but I stumbled upon this semantics issue while trying to make a REST API.
10.4.4 403 Forbidden
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
Nowadays, someone says «403» and a permissions or authentication issue comes to mind, but the spec says that it’s basically the server telling the client that it’s not going to do it, don’t ask it again, and here’s why the client shouldn’t.
9.6 PUT
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
As an argument against other answers, to use any non- 4xx error code would imply it’s not a client error, and it obviously is. To use a non- 4xx error code to represent a client error just makes no sense at all.
It seems that 409 Conflict is the most common answer here, but, according to the spec, that implies that the resource already exists and the new data you are applying to it is incompatible with its current state. If you are sending a POST request, with, for example, a username that is already taken, it’s not actually conflicting with the target resource, as the target resource (the resource you’re trying to create) has not yet been posted. It’s an error specifically for version control, when there is a conflict between the version of the resource stored and the version of the resource requested. It’s very useful for that purpose, for example when the client has cached an old version of the resource and sends a request based on that incorrect version which would no longer be conditionally valid. «In this case, the response representation would likely contain information useful for merging the differences based on the revision history.» The request to create another user with that username is just unprocessable, having nothing to do with any version conflict.
For the record, 422 is also the status code GitHub uses when you try to create a repository by a name already in use.
«Directory already exists» when trying to clone git repo for first time #122
Comments
quvide commented Aug 25, 2015
When trying to clone a repo for the first time, it gives a message «Directory already exists». When I select «delete directory» it gives «Message from jgit: Attempt to get length of null array».
The text was updated successfully, but these errors were encountered:
mpnordland commented Feb 1, 2016
I have a similar problem, i choose the recommended hidden option, and then enter my ssh server details and then attempt to clone. It prompts to delete the directory, which I agree to, but then nothing happens.
pdroalves commented Feb 5, 2016
pdroalves commented Feb 6, 2016
I solved my problem. For some stupid reason I was trying to use my public ssh key instead of the private key. I replaced it and it worked.
As suggestion, we need an alert about using an invalid ssh key.
powellc commented Feb 15, 2016
I just double checked all my information and the key I was using and nothing is working. Just sits there after asking to delete the current directory 🙁
zeapo commented Feb 23, 2016
I deleted the previous comment as it was intended for another issue. Sorry.
Are you trying to clone into the internal store?
mpnordland commented Feb 23, 2016
Yes. I worked around this issue by downgrading and messing around with the older version. I originally experienced this again, but later it worked.
Sent from my Android device with K-9 Mail. Please excuse my brevity.
tuxick commented Jun 8, 2016
Same problem here, first «Directory already exists», telling it to delete and then the Internal Exception: «Message from jgit: Attempt to get length of null array»
bjmgeek commented Jun 20, 2016
I had the same issue. I have multiple user profiles on my android device (LG Nexus 5 with Android 6.0.1) and I thought it may have been related to that (I already have password store installed on my main user profile, and I was trying to install on a new user).
adskankster commented Jul 12, 2016
Running on aliendalvik on a Jolla, but as I say, it did work originally.