How to flatten nested MongoDB fields in Forest Admin
In this article, we take a look at how you can flatten your nested fields in Forest Admin when working with MongoDB databases.
Depending on the type of database you use for your app, you might or might not have embedded or nested objects within your data. When dealing with NoSQL databases like MongoDB, users usually work with a large number of nested objects, and the fields inside them.
In the past, Forest Admin could only handle these nested fields through a JSON editor, and functions such as CRUD, filtering, and being able to use related data were not available. The usual solution to this problem was to create a Smart Field for each of the nested fields that would turn them into normal fields — however, we felt like this proved to be quite inconvenient for our users, which is why we’re introducing the ability to flatten fields in Forest.
How does it work?
You can flatten embedded objects using the flatten
command. All you need to do is find the embedded object you’re trying to flatten, and specify the level of flattening when considering your embedded object: this will determine how far down the embedded objects we’re going to go in terms of flattening. By default, this value is the maximum one, which means all fields are flattened. So, for example, where “users” is a collection, and “user: {“ is a sample user:
user: {
address: {
street: 'backer'
country: {
code: 'FR',
name: 'France',
}
}
}
with flatten address lvl 0
user: {
address-street: 'backer'
address-country: {
code: 'FR',
name: 'France',
}
}
with flatten address and unspecified level
user: {
address-street: 'backer'
address-country-code: 'FR',
address-country-name: 'France',
}
If the object you’ve chosen contains a reference, it will be resolved. If the object contains an array of references, it will be transformed into related data, which you’ll be able to see and use in Forest like this.
Once you flattened a field, it will be brought to the root level, causing them to be automatically considered a normal field for all intents and purposes. This means that not only will they appear in the collection they’re in (don’t worry, you can hide them on the UI anytime), but you’ll also be able to perform all actions you normally would for a normal field, including CRUD, filtering, scopes, searching, sorting, segmenting, and more.
If you have any questions or would like our help with anything related to your Forest setup, don’t forget to reach out to us on our Developers Community, or get in touch with us on Twitter, Facebook, or Linkedin.