Reputation: 1476
creating a document with status as pending and generated-token then send mail
and immediately after sending mail retrieving document by generated-token value and changing the previous status pending to unverified.
Even though for updating the document status, first retrieved the existing document and then only updating it, still end up in creating two different documents for both the status.
@Document
public class VerificationInfo {
private LoginInfo user;
private String token;
private String verificationStatus = VerificationStatus.PENDING.getVerificationStatus();
}
daoService
public void updateStatus(VerificationInfo verificationToken, String status) {
VerificationInfo vt = verificationRepository.findByToken(verificationToken.getToken()).get(0);
vt.setVerificationStatus(status);
verificationRepository.save(vt);
}
repository
@Repository
public interface VerificationRepository extends MongoRepository<VerificationInfo, String> {
List<VerificationInfo> findByToken(String token);
List<VerificationInfo> findByUser(LoginInfo user);
}
db entries
{ "_id" : ObjectId("5f4e7486664e197f3d745b17"), "token" : "c82907b7-e13e-484d-89cf-92ea394b6f6d", "verificationStatus" : "pending", "_class" : "com.models.VerificationInfo" }
{ "_id" : ObjectId("5f4e748b664e197f3d745b18"), "token" : "c82907b7-e13e-484d-89cf-92ea394b6f6d", "verificationStatus" : "unverified", "_class" : "com.models.VerificationInfo" }
Upvotes: 0
Views: 1197
Reputation: 8894
If the status is correct, the problem with you identification of the document (_id).
public class VerificationInfo {
@Id
ObjectId _id;
// Other fields
}
Here we set a unique id to each document. So when you create a object, it will create a new document. If the _id already exists in database, then it will update the document based on the particular id.
1. There is no _id present in the model class
You extends MongoRepository<VerificationInfo, String>
, the second parameter is the type of id
. But there is no any id
found in your model class. (Usually we use ObjectId
, but String
also can be given)
2. It will always create new document when you get data from frontend
Since you don't have id, when you pass a data to updateStatus(VerificationInfo verificationToken, String status)
, it will create new id
and set the data, that's why you always getting new document.
Suppose you are sending the data with existing id
, then the existing document will be updated based on given id
Upvotes: 1