Woodshop
Search…
Migrate Mongoose files

What has changed from previous versions

In version 8 we introduced the application-wide scopes and dynamic smart action form along with hooks on bulk and global smart actions.
Since version 7, we introduced a new structure of our generated projects to ease the support of multiple databases. This new structure is the major change we need to consider to correctly perform the migration of your files.
The idea of this document is to guide you through the project architecture and make as few changes as possible to benefit from TypeScript.
The key concepts to handle multi databases are the following:
    A configuration file to export your connection options to your databases.
    A dynamic loading mechanism to dynamically load your models depending on their database connections.
The files related to these key concepts are the files under the /models and the /config directories. Let's handles these files first.

Define your models

What to achieve:
    Export an interface representing your model in TypeScript
    Export a mongoose Schema corresponding to your interface
To migrate our JavaScript models to TypeScript, we will take the following model generated by lumber as an example:
models/client.js
1
module.exports = (mongoose, Mongoose) => {
2
3
const schema = Mongoose.Schema({
4
'status': String,
5
'firstname': String,
6
...
7
'lastname': String,
8
}]
9
}, {
10
timestamps: false,
11
});
12
13
return mongoose.model('clients', schema, 'clients');
14
};
Copied!
As you can see, it has been generated to be loaded dynamically. This file actually exports a function accepting a mongoose connection as an argument, to link the model to it. This will not be required anymore.
To make this model work using TypeScript, we first need to declare an interface representing data we can encounter in it. We also need to export the mongoose Schema that describes the same data from the interface. Mongoose can only work with schemas, but TypeScript can't correctly infer types from this kind of structure. This is why we need both the interface for coding and the schema for mongoose.
models/client.ts
1
import { Schema, Document } from "mongoose";
2
3
export interface IClient {
4
status: string,
5
firstname: string,
6
...
7
lastname: string,
8
}
9
10
const ClientSchema = new Schema<IClient>({
11
status: { type: String, required: true },
12
firstname: { type: String, required: true },
13
...
14
lastname: { type: String, required: true },
15
}, {
16
timestamps: false,
17
});
18
19
export ClientSchema;
Copied!
Do note the usage of the interface in the Schema creation (line 10), this is how we link the TypeScript world to the mongoose world. Also, note that the model is not created in this file anymore, this will be done in the models/index.ts we are about to change in the next section.

Connect to your databases

Goals:
    Connect to each of your databases
    Import models definition in those connections
The database connections are configured in config/databases.js. Here is an example of a fresh new generated project with one connection:
config/databases.js
1
const path = require('path');
2
3
const databaseOptions = {
4
useNewUrlParser: true,
5
useUnifiedTopology: true,
6
};
7
8
module.exports = [{
9
name: 'default',
10
modelsDir: path.resolve(__dirname, '../models'),
11
connection: {
12
url: process.env.DATABASE_URL,
13
options: { ...databaseOptions },
14
},
15
}];
Copied!
This file is responsible for providing the database connections with the corresponding options. In the end, this file should export an array of connections. If we translate this file into TypeScript, we have to export the same database structure, here is an example:
config/databases.ts
1
import { ConnectionOptions } from "mongoose";
2
import { DatabaseConfiguration } from "forest-express-mongoose";
3
import { resolve } from 'path';
4
5
const databaseOptions: ConnectionOptions = {
6
useNewUrlParser: true,
7
useUnifiedTopology: true,
8
};
9
10
const databasesConfiguration: DatabaseConfiguration[] = [{
11
name: 'default',
12
modelsDir: resolve(__dirname, '../models'),
13
connection: {
14
url: process.env.DATABASE_URL,
15
options: { ...databaseOptions },
16
},
17
}];
18
19
export default databasesConfiguration;
Copied!
Now your connections are configured, let's load the models for every connection.
A generated project uses a dynamic model instantiation approach. To do so, the index.js file under the models folder is responsible for browsing your models and for loading them. Then, the file exports the models and you can access them from anywhere using const { client } = require('./models');. This works pretty well in JavaScript because you are not forced to strictly type what models exports. However using TypeScript, this kind of approach is not ideal because the dynamic part of this approach can not be typed, and thus, TypeScript will raise errors stating that models has no exported member client . Let's break down the index.js file step by step to understand what is going on inside.
models/index.js
1
const fs = require('fs');
2
const path = require('path');
3
const Mongoose = require('mongoose');
4
5
const databasesConfiguration = require('../config/databases');
6
7
const connections = {};
8
const db = {};
9
10
databasesConfiguration.forEach((databaseInfo) => {
11
const connection = Mongoose.createConnection(databaseInfo.connection.url, databaseInfo.connection.options);
12
connections[databaseInfo.name] = connection;
13
14
const modelsDir = databaseInfo.modelsDir || path.join(__dirname, databaseInfo.name);
15
fs
16
.readdirSync(modelsDir)
17
.filter((file) => file.indexOf('.') !== 0 && file !== 'index.js')
18
.forEach((file) => {
19
try {
20
const model = require(path.join(modelsDir, file))(connection, Mongoose);
21
db[model.modelName] = model;
22
} catch (error) {
23
console.error(`Model creation error: ${error}`);
24
}
25
});
26
});
27
28
db.objectMapping = Mongoose;
29
db.connections = connections;
30
31
module.exports = db;
Copied!
Indexing models by their name (line 21) is the concept we want to avoid to benefit from TypeScript and code completion. Because it is dynamic at run time, TypeScript can't infer the structure of the exported models and thus, fails at compilation time.
For every connection you configured, this code will create the connection to the database and dynamically load the associated models (from line 10 to line 14). We have no choice but to break this dynamic approach and load the models by hand to be able to export them later on. The new static approach will allow TypeScript to infer the type of the exported object, and thus, will provide us with clean code completion.
models/index.ts
1
import * as Mongoose from 'mongoose';
2
import databasesConfiguration from '../config/databases';
3
import { ClientSchema, IClient } from '../models/clients';
4
5
const connections: Record<string, Mongoose.Connection> = {};
6
const objectMapping = Mongoose;
7
8
const connection = Mongoose.createConnection(databasesConfiguration[0].connection.url, databasesConfiguration[0].connection.options);
9
connections[connection.name] = connection;
10
11
const Client = connection.model<IClient>('clients', ClientSchema, 'clients');
12
13
export {
14
objectMapping,
15
connections,
16
Client,
17
};
Copied!
If you still want to work with such a dynamic loading mechanism, please ensure that either you don't generate .map.js files, or ensure you skip these files in the filter in the original index.jssnippet. Otherwise, you will encounter an error at runtime such as Model creation error: SyntaxError: Unexpected token ':'
Do note that we still export connections and Mongoose as objectMapping . This is still mandatory to allow your app to be correctly initialized.
This might look tedious at first, but in the end, you are now able to use your models with code completion like the following:
routes/clients.ts
1
import { Client } from '../models'
2
3
...
4
5
Client.findById(..)..
Copied!

Initialize your Liana

The middlewares/forestadmin.js is pretty straightforward and just needs to be translated from .js to .ts . See the following snippet:
middlewares/forestadmin.ts
1
import * as chalk from 'chalk';
2
import { join } from 'path';
3
import { init, LianaOptions } from "forest-express-mongoose";
4
import { objectMapping, connections } from '../models';
5
import { Application } from "express";
6
7
export = async function forestadmin(app: Application): Promise<void> {
8
const lianaOptions: LianaOptions = {
9
configDir: join(__dirname, '../forest'),
10
envSecret: process.env.FOREST_ENV_SECRET,
11
authSecret: process.env.FOREST_AUTH_SECRET,
12
objectMapping,
13
connections,
14
}
15
16
app.use(await init(lianaOptions));
17
18
console.log(chalk.cyan('Your admin panel is available here: https://app.forestadmin.com/projects'));
19
20
return;
21
};
Copied!

Override your routes

For your routes' code, nothing, in particular, should be changed in terms of structure. Just translate your JavaScript code into TypeScript.
To benefit from code completion, just ensure to use your models' interface when you manipulate your records. Here is an example with the client model we have been using in this documentation:
routes/clients.ts
1
import {
2
ForestRequest,
3
...
4
RecordGetter,
5
} from 'forest-express-mongoose';
6
import { Client } from '../models';
7
import { IClient } from '../models/clients';
8
9
...
10
11
router.get('/clients/:recordId', permissionMiddlewareCreator.details(), async (request: ForestRequest, response) => {
12
const { user, query } = request;
13
const clientGetter = new RecordGetter<IClient>(Client, user, query);
14
const client = await clientGetter.get(request.params.recordId);
15
const clientSerialized = await clientGetter.serialize(client);
16
response.json(clientSerialized);
17
});
Copied!
Note the request: ForestRequest to have access to user and query
After line 8, the type of the client record should be well inferred and your IDE should provide some code completion, related to the IClient interface. This is because we passed the interface to RecordGetter as a generic type.

Customize your collections

For your collections' code, nothing, in particular, should be changed in terms of structure.
The difference you will feel now is the code completion provided by your IDE, in conjunction with our Types. For example, If you start to create a smart field, you should be guided and a list of possible attributes to configure should be provided.
Last modified 1mo ago