According to the official MongoDB docs, A MongoDB view is a queryable object whose contents are defined by an aggregation pipeline on other collections or views.
In other words we can say that views can be created on existing collection in MongoDB using custom aggregate queries passing as the pipeline stages
Note: MongoDB does not support write operations against views as it is Read-only object.
Primary usage of the views is to showcase the collection data in other form or take only selected attributes from the collection and use it to create custom views on that specific collection.
Developer can also use MongoDB views for query optimization and performance improvement for large collection of data.
Now let’s jump over to creating MongoDB views in Loopback4?
Creating MongoDB views is little bit tricky when it comes to Node JS framework Loopback4.
If you are stuck on creating views in MongoDB in Loopback4 you are at the right place.
Follow below steps to create MongoDB views in Loopback4 ? (Here assume that loopback4 application is created and there are some existing collections present in Database)
Step 1: Create Observer using below command
lb4 observer
Enter observer name and observer group and hit enter.
Reason: MongoDB views will be created when application is started.
Step 2: Open newly created observer file. Here you can see the start() method.
Step 3: Before creating views loopback4 requires the datasource object injected in constructor.
Paste below code in constructor of the observer file (for MongoDB datasource).
inject('datasources.MongoDB') public dataSource: MongoDBDataSource
Step 4: In async start() method use below code to create MongoDB views.
Please take reference from the below screenshot
try { await this.dataSource?.connector?.connect((err, db) => { db.createCollection('<viewName>', { viewOn: '<collectionName>', pipeline: [ // add your aggregate queries to creating view { .... }, { ..... } ] }); }); } catch (error) { console.error(error); }
Here ViewName points to the name of the view which will be created and CollectionName points to the name of the existing Collection or Model on which that new view will be created.
Above code snippet is used to create single view in MongoDB.
If developer wants to create multiple views then use try catch block around each view as it can throw error for namespace already exist for existing views present in MongoDB.
Quick Links