Firestore "updateData" removes all the fields in document - swift

In my prpject I have a "employees" collection where every employee document containes fileds like: firstName, lastName, zipCode, refreshToken etc.
When trying to update just a value of refreshToken i use 'updateData' like shown in documentation docs
my code:
static func updateToken(token:String){
Firestore.firestore().collection("companies").document(self.user.companyId).collection("employees")
.document(self.user.employeeId).updateData(["refreshToken" : token])
}
but that removees all other values of employee document (firstName, lastName, zipCode etc) and just new value of refreshToken exist in the node after operation. Am I doing something worng or I missunderstod idea of "updateData"?

If you want to update the value of a field and if the document does exist, its contents will be overwritten with the newly provided data, unless you specify that the data should be merged into the existing document, as follows:
Firestore.firestore().collection("companies").document(self.user.companyId)
.collection("employees").document(self.user.employeeId)
.setData(["refreshToken" : token], merge: true)
}
See, I have used setData() function instead of updateData().

Related

Firestore: Save document ID into the Field

I'm using Swift here and confused about how to save the document ID into itself field. Here is an example :
I have a collection named "menu"
here we can focus on the one and only document in the "menu" collection which saved the name field "ayam goreng". How do i save the document ID "
7D3fuw3fri6oj287SySW" to the field named "menu_id" inside the document?
As shown in the documentation on adding a document:
In some cases, it can be useful to create a document reference with an auto-generated ID, then use the reference later. For this use case, you can call doc():
let newCityRef = db.collection("cities").document()
// later...
newCityRef.setData([
// ...
])
In your case, you can then get the document ID from the new ref with:
newCityRef.documentId

How to get the document id from a firestore document in Flutter?

In my App a user can have many different gymplans. So I have a collection where every gymplan has his own document. When creating a new plan I want to store the document id inside the document so that I have access to this document with the id.
When creating a new document firestore automatically create a unique id which is fine. But how can I get this id inside my code? So far my code to create a new plan looks like this:
Future createPlan(String planName, List exerciseNames, List rows) async {
return await usersCol.doc(myUser.uid).collection('plans').add({
'planId': /// here i want to save the document id firestore creates
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});
}
You'd have to create the document first. Then use set() instead of add(). So:
final ref = usersCol.doc(myUser.uid).collection('plans').doc();
return await ref.set({
'planId': ref.id,
'name': planName,
'exerciseNames': exerciseNames,
'rows': rows,
});

Update entire document in mongodb using morphia

I have document which I need to update but updated parameters are not same all the time it depends on user. So how can I update document or replace whole document with new values based on id.
You wrap your updated values in a Map the set the update:
Map<String, Object> updateInfo; // Key is db column name, value is updatedValue
Then create update operations:
Query<Entity> filter = datastore.createQuery(Entity.class)
.field("_id", id);
UpdateOperations<Entity> updateOps = datastore.createUpdateOperations(Entity.class);
updateInfo.entrySet().forEach(e -> updateOps.set(e.getKey(), e.getValue());
datastore.update(filter, updateOps);
By this way, you can update entity with any number of fields

spring-data-mongo, how to return _id back for saved objects from mongo?

I am newbie to the Spring Data mongo. I have documents which has same FirstName say John, but MiddleName and LastName are different.
Also from UI, some students populating data (feeding data via forms) which has also FirstName say John and again MiddleName and LastName would be different.
Now, when I am saving User Object (which has FirstName, MiddleName, LastName, Age, Sex etc..etc..) into mongo using MongoTemplate. I need to return back "_id" (which mongo create by default if we don't provide it explicitly) of those each saved User object.
Could you please provide any example / guidance? Please help.
If you are saving with mongo template your object Id will be set after insertion (as Oliver Gierke has writen) of the object so you can do it like this.
//User object annotated with #Document
User user = new User(String name);
user.setWhatever(something);
mongoTemplate.save(user);
//now the user object should be populated with generated id;
return user.getId();
but you can use normal CrudRepository and use it with
<mongo:repositories base-package="your.package" />
Spring Data MongoDB will automatically populate the identifier property of your domain object with the generated identifier value.
#Document
class User {
ObjectId id; // by convention, use #Id if you want to use a different name
String firstname, lastname;
…
}
If an object of this class is persisted with the id property set to null, the object will have the property set after it has been persisted via MongoTempalte.
All of this is also described in the reference documentation.

Is there a way to update a database field based on a list?

Using JPA, I have a list of entries from my database :
User(id, firstname, lastname, email)
That I get by doing:
List<User> users = User.find("lastname = ?", "smith");
And I'd like to update all in one request, by doing something like this :
"UPDATE USER SET email = null IN :list"
and then set the parameter "list" to users
Is it possible? if so, how?
Thanks for your help :)
Well, you could embed the query that you used to obtain list in the where clause of the update.
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName = :?)
By doing this you'd be doing the query to search the list and the update in single update query.
How do you like that? Do you think this could work?
-EDIT-
Since you want to use the original list of items instead of a list just retrieved from the database, you can still ensure you build the original list like this
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName IN(:originalList))
Then when you invoke it, you can do something like this:
Collection<String> originalList = Arrays.asList("Kenobi", "Skywalker", "Windu");
query.setParameter("originalList", originalList);
By this, you can still ensure the query will only contain items in your original list and not any possible new item from the database, provided that that last name is a candidate key in the database, otherwise I would recommend that you use the ID for the subquery instend of the last name.
if you have jpa+hibernate you can use entityManager.createQuery() for creating hql query
like that:
String hql = "UPDATE Supplier SET name = :newName WHERE name IN :name";
entityManager.createQuery(hql);