how we would know if document was saved in Mongodb after save() method?

瘦欲@ 提交于 2019-12-10 13:37:04

问题


I am saving my document in MongoDb and using save method with class,collection name param.

All the methods of save and insert are void return type. then how i can know that my document was saved or not.

Is it that i have to re-query to check whether my document was saved. I just need any return value to see if it was saved.

Moreover i am using Spring Data for Mongo to do operations.


回答1:


It depends on what WriteConcern are you using. If you use WriteConcern.ACKNOWLEDGED, the operation will wait for an acknowledgement from the primary server, so if no exception is raised, the record has been saved correctly. Otherwise you should be able to query WriteResult

WriteResult writeResult=mycollection.insert(record);
if (writeResult.getError() != null) {
    throw new Exception(String.format("Insertion wasn't successful: %s",writeResult));
 }



回答2:


org.springframework.data.mongodb.repository.MongoRepository

returns a list of the saved objects:

<S extends T> List<S> save(Iterable<S> entites);

or in

CrudRepository

you have

<S extends T> S save(S entity);

which provides the saved object. That object will have a whatever field you annotated with @Id with a value filled in different to null after it has successfully been persisted.



来源:https://stackoverflow.com/questions/33867680/how-we-would-know-if-document-was-saved-in-mongodb-after-save-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!