One potential solution is to extract the BSON schema from mongodb and convert it into a "regular" JSON schema since generating typescript interface specs dynamically may not be a standard practice. The key focus here lies in mapping BSON types to equivalent JSON types.
db = db.getSiblingDB("testX");
function convertBSONtoJSON(holder, spot, value) {
if(value == null) {
return;
}
if(Array.isArray(value)) {
for(var jj = 0; jj < value.length; jj++) {
convertBSONtoJSON(value, jj, value[jj]);
}
} else if(typeof value == "object") {
processObject(value);
} else {
if(spot == 'bsonType') {
if(value == 'int' || value == 'long') {
holder['type'] = 'integer';
} else if(value == 'date') {
holder['type'] = "string";
holder['format'] = "date-time";
} else if(value == 'decimal') {
holder['type'] = "string";
holder['format'] = "decimal";
} else {
holder['type'] = value;
}
delete holder['bsonType']
}
}
}
function processObject(obj) {
Object.keys(obj).forEach(function(k) {
convertBSONtoJSON(obj, k, obj[k]);
});
}
var collectionInfo = db.getCollectionInfos( { name: "myColl" } );
if(collectionInfo.length == 1) {
validationExpr = collectionInfo[0].options.validator;
if(validationExpr != undefined) {
processObject(validationExpr);
print(validationExpr);
}
}
A more innovative approach could involve introducing flexible type handling capabilities in json2ts
. This would enable seamless conversion of unknown types like date
, decimal
, etc., by utilizing a function to provide the necessary type definitions for generating complete interfaces.