Reputation: 1689
I have a JSON schema as shown below which I am sending to my backend via websocket.
{
"type": "object",
"properties": {
"user": {
"$ref": "#/definitions/user"
}
},
"required": [
"user"
]
}
My bean class for this is defined as
class Schema{
private String type;
private String[] required;
Private Map<String, Object> properties;
//getter and setter
}
Now I want to store this in mongodb but when I try to do that I get below exception
org.springframework.dao.DataIntegrityViolationException: Write failed with error code 55 and error message 'The DBRef $ref field must be following by a $id field'; nested exception is com.mongodb.WriteConcernException: Write failed with error code 55 and error message 'The DBRef $ref field must be following by a $id field'
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:85) ~[spring-data-mongodb-1.10.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135) ~[spring-data-mongodb-1.10.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:481) ~[spring-data-mongodb-1.10.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.saveDBObject(MongoTemplate.java:1101) ~[spring-data-mongodb-1.10.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.doSave(MongoTemplate.java:1034) ~[spring-data-mongodb-1.10.1.RELEASE.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.save(MongoTemplate.java:981) ~[spring-data-mongodb-1.10.1.RELEASE.jar:na]
I am guessing that $ref is not a valid key name to be used in mongodb but it is a valid key for JSON Schema based on Open API specifications and I want to tore it as is. Is there any solution for this?
Upvotes: 0
Views: 1018
Reputation: 1689
As I was sending the data through websocket which transmits it as a string, I am replacing $ref
with some string (say ##ref##
) which is a valid key name for mongodb.
strData = strData.replace(new RegExp('"\\$ref":', 'g'), '"##ref##":');
self.stomp.send('/app/execute', {}, strData);
And when I receive it from backend, I again replace ##ref##
with $ref
.
body = body.replace(new RegExp('"##ref##":', 'g'), '"$ref":');
Upvotes: 0
Reputation: 30819
As per this mongodb JIRA, you can't save a key that contains .
or starts with $
. So, I believe the only solution here is to manually escape $
before storing the object into mondogb
and remove \\
while retrieving it.
You can write this logic in the layer that deals with storage/retrieval of these objects.
Upvotes: 1