Export data from a MongoDB .realm file
In my case, I had data stored in a Realm file that I needed to re-export to JSON.
First of all we’ll need Realm Studio. Set up, open the Realm file and then export the models, as shown:
Then let’s set up a Node environment:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash
nvm install 10
## exit and re-enter shell, or run the ./source
Then install the node module:
nvm use 10
npm -g install realm
Great. Now, armed with your list of models, determine your top-level object that you’re extracting from the database. In our case, we are extracting ‘Banana’ type objects.
const Realm = require('realm');
// required for writing our output file
const fs = require('fs');
// this is the 'models' file from Realm
const models = require('./models.js');
function writeObjects(inputRealm, realmName) {
let a = [];
for (let item of inputRealm) {
a.push(JSON.parse(JSON.stringify(item)));
}
fs.writeFile(`out/${realmName}.json`, JSON.stringify(a), 'utf8', function(err) {
if (err) {
console.log(`error while writing file ${realmName}`)
}
});
}
Realm.open(
{
schema: [
models.Banana,
models.Example,
models.Example2
]
}
)
.then(
realm => {
writeObjects(realm.objects('Banana'), 'Banana');
// further objects can be written out here of course
realm.close();
}
)
.catch(error => {
console.log(error);
}
);
To run, make sure you’ve created the output directory mkdir out
and then it’s just a
case of executing node script.js
. Run with switch --inspect-brk
and open Chrome at
URL chrome://inspect
to connect to debugger, pause script execution and inspect
runtime vars if need be.
JSON output should be available after execution under ./out
.