Reputation: 10109
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?
Upvotes: 1
Views: 3077
Reputation: 276085
syntax to export the mongoose model from ./models/user.ts and import it from another file?
import mongoose = require('mongoose');
var userSchema = new mongoose.Schema({ ... });
var User : mongoose.Model<any> = mongoose.model("User", userSchema);
export = User; // EXPORT
import mongoose = require('mongoose');
var userSchema = new mongoose.Schema({ ... });
var User = mongoose.model("User", userSchema);
export default { User }; // EXPORT
import User = require("./models/User"); // Note the `.` to make it relative.
Upvotes: 1
Reputation: 16300
You want to simply prepend export
to your model.
import mongoose from 'mongoose';
var userSchema = new mongoose.Schema({ ... });
export default var User : mongoose.Model<any> = mongoose.model("User", userSchema);
Or if you want to stick with the CommonJS syntax you can export.modules = User;
Upvotes: 0