T. Webster T. Webster - 6 months ago 68
Node.js Question

How to export a Mongoose model from a CommonJS module in TypeScript NodeJS app

I have a model defined in

models/user.ts


import mongoose = require('mongoose');
var userSchema = new mongoose.Schema({ ... });
var User : mongoose.Model<any> = mongoose.model("User", userSchema);


Normally in JavaScript, in order to use the model
User
in a NodeJS app
app.js
,

In JavaScript I would ordinarily use
module.exports = User
from
./models/user.js
, followed by
require
from the file I want to use
User
from.

e.g.

var user = require('./models/user')


however this is not recognized in TypeScript (I get transpiler errors), and neither is

import User = require("/models/User")


although that would work if I was exporting, say a class, from
/models/user.ts
like

export class User { ... }


What is the syntax to export the mongoose model from
./models/user.ts
and import it from another file?

Answer

syntax to export the mongoose model from ./models/user.ts and import it from another file?

Export

import mongoose = require('mongoose');
var userSchema = new mongoose.Schema({ ... });
var User : mongoose.Model<any> = mongoose.model("User", userSchema);
export = User;  // EXPORT

Import

import User = require("./models/User"); // Note the `.` to make it relative.