ES6: Module '"mongoose"' has no default export - node.js

Using ES6 Imports & Exports I feel like I should be able to declare the import as
import mongoose, { Schema, Document } from 'mongoose'; but I get the error Module '"mongoose"' has no default export.
The below does work but it clearly isn't the right way to go about this import. The export default id like to remove too.
import * as mongoose from 'mongoose';
import { Schema, Document } from 'mongoose';
export interface IUser extends Document {
email: string;
password: string;
}
const UserSchema: Schema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
export default mongoose.model<IUser>('User', UserSchema);
And then im using it with
import UserModel, { IUser } from '../models/example'
import * as bcrypt from 'bcrypt';
class User {
static register = async (req: Request, res: Response) => {
const email = req.body.email;
const password = req.body.password;
const alreadyRegistered = await UserModel.findOne({email}).exec();
if (!alreadyRegistered) {
const hashedPassword = await bcrypt.hash(password,10);
if (!hashedPassword) {
res.status(500).send({ message: "Failed to encrypt your password" });
} else {
const user = new UserModel(<IUser>{email:email, password:hashedPassword});
const saved = await user.save();
if (!saved) {
res.status(500).send({ message: "Failed to register you" });
} else {
res.status(200).send({ message: "You are now registered" });
}
}
} else {
res.status(400).send({ message: "You have already registered" });
}
};
}
export {User}

I came across this issue and fixed it by adding the following to tsconfig.json
"esModuleInterop": true
Then I could import as normal
import mongoose from 'mongoose'

Try This
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
module.exports = mongoose.model('User', UserSchema);
2nd Way -
import * as mongoose from 'mongoose';
type UserSchema = IUser & mongoose.Document;
const User = mongoose.model<UserSchema>('User', new mongoose.Schema({
email : { type: String, required: true, unique: true },
password: { type: String, required: true }
}));
export = User;

Make sure that you have "allowSyntheticDefaultImports": true, in tsconfig.json file.
Reference: https://github.com/microsoft/TypeScript-React-Starter/issues/8#issuecomment-301265017

I am not sure how you are compiling the typescript but it should work just fine with the defaults set in tsconfig.json file.
generate tsconfig.json in your project's root directory by running tsc --init (as mentioned, you can use defaults for this to work with target set even to es5)
now you can run tsc -w or ts-node index.ts or however you prefer to build/run your code
Note that the index.ts file must be either in your project's root or you will need to specify the path in the tsconfig.json (the rootDir options which is commented out by default and uses path relative to the tsconfig file).
Also note that if you are running tsc -w or some other command that compiles/runs the code from some other directory than the one where tsconfig.json is located, you will need to provide a path to it, i.e. tsc -p path_to_config -w

I Have the same issue I noticed that I missed the tsconfig.json

import { model, Schema } from 'mongoose';
...
export default model<IUser>('User', UserSchema);

Related

Mongoose with Typescript: Trying to split schema, methods and statics in seperate files, problem with this has type any and is hidden by container

i'm trying to split up my single-files mongoose schemas with statics and methods.
(I found this tutorial for splitting: https://medium.com/swlh/using-typescript-with-mongodb-393caf7adfef ) I'm new to typescript but love the benefits it gives while coding.
I've splitted my user.ts into:
user.schema.ts
user.model.ts
user.types.ts
user.statics.ts
user.methods.ts
When i change this lines in my schema file:
UserSchema.statics.findUserForSignIn = async function findUserForSignIn(
email: string
): Promise<IUserDocument | null> {
const user = await this.findOne({ email: email });
if (!user) {
return user;
} else {
return user;
}
}
to UserSchema.statics.findUserForSignIn = findUserForSignIn;
and copy the Function findUserForSignIn to user.statics.ts, Typescript says "'this' implicitly has type 'any' because it does not have a type annotation" and "An outer value of 'this' is shadowed by this container."
So, how to add this properly? If i add this to findUserForSignIn with IUserModel as Type, add null to Promise return type it would nearly work:
export async function findUserForSignIn(
this: IUserModel,
email: string
): Promise<IUserDocument | null> {
const user = await this.findOne({ "person.email": email });
return user;
}
And if i add this to receiving function parameters: users gets to type IUserDocument, before it was any. I think its nice to have typeclear, not just any.
But: in user.schema.ts the UserSchema.statics.findUserForSignIn gets a red line from typescript. Type can not be assigned to other type. The signature of this is not identical.
If i change the type of this to any, all is okay. But the return is not longer from type IUserDocument. Mabye its okay if i get over an aggregation pipeline and only set the Promise-Return-Type. But that this: any gets hinted in yellow by typescript.
And, another question: if i pass this as first and email as second parameter, why is only one parameter required?
Anyone has an "how to" for me? Or can explain what i've done wrong? Or what is the best way? Or is it not possible to split statics and methods in seperate files from schema?
Original files:
user.schema.ts
import { Schema } from "mongoose";
import { PersonSchema } from "./person.schema";
import { findUserForSignIn } from "./user.statics";
import { IUserDocument } from "./user.types";
const UserSchema = new Schema<IUserDocument>({
firstname: {
type: String,
required: true,
},
lastname: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
});
UserSchema.statics.findUserForSignIn = findUserForSignIn;
export default UserSchema;
user.types.ts
import { Document, Model } from "mongoose";
import { IPerson } from "./person.types";
export interface IUser {
firstname: string;
lastname: string;
email: string;
}
export interface IUserDocument extends IUser, Document {}
export interface IUserModel extends Model<IUserDocument> {
findUserForSignIn: (email: string) => Promise<IUserDocument>;
}
user.model.ts
import { model } from "mongoose";
import UserSchema from "./user.schema";
import { IUserDocument, IUserModel } from "./user.types";
const User = model<IUserDocument>("User", UserSchema) as IUserModel;
export default User;
user.statics.ts
import { IUserDocument } from "./user.types";
export async function findUserForSignIn(
email: string
): Promise<IUserDocument | null> {
const user = await this.findOne({ email: email });
if (!user) {
return user;
} else {
return user;
}
}
The only way seems to change the user.statics.ts
export async function findUserForSignIn(
this: Model<IUserDocument>,
email: string
): Promise<IUserDocument | null> {
console.log("E-Mail", email);
const user = await this.findOne({ email: email });
return user;
}
this has to be of type Model
Then code seems to be okay.

Typescript : File '/accounts.ts' is not a module in a nodejs api

I have seen over this issue and found a few answers but none of the solutions solves my problem.
Below is my code model file
// accounts.ts
const mongoose = require('mongoose');
var autoincrement = require('simple-mongoose-autoincrement');
const Accounts = mongoose.Schema(
{
id: { type: mongoose.Schema.Types.ObjectId, required: true, unique: true },
accountDetails: { type: String },
// other collection properties goes here.
}
);
Accounts.plugin(autoincrement, { field: 'id' });
module.exports = mongoose.model('Accounts', Accounts);
Below is my repository code
//AccountsRepository.ts
// import { Accounts } from "../../models/accounts";
// import Accounts from "../../models/accounts";
I have tried the above two methods of imports but I get the exception as below
File 'myPath/accounts.ts' is not a module.ts(2306)
I face the same issue in my other files as well.
//AccountsRouter.ts
import express from "express";
import accountsController from "../../controller/accountscontroller";
const accountsRouter = express.Router();
accountsRouter.get("/details", accountsController.getDetails);
exports = accountsRouter;
//App.ts
`import accountsRouter from "./accounts/accountsrouter";` --> this gives the error as below
Module 'myPath/accouts/accountsrouter"' has no default export.ts
I don't want to make a default export in my accountsRouter.
I tried:
I tried to change the ways of export like using
module.export = accountsRouter
You can try with brackets
....
export { accountsRouter }
And then import the module like :
import { accountsRouter } from "./accounts/accountsrouter"

Cannot overwrite 'user' model once compliled when adding a second schema to a database. [duplicate]

Not Sure what I'm doing wrong, here is my check.js
var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
var user = mongoose.model('users',{
name:String,
email:String,
password:String,
phone:Number,
_enabled:Boolean
});
user.find({},{},function (err, users) {
mongoose.connection.close();
console.log("Username supplied"+username);
//doSomethingHere })
});
and here is my insert.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/event-db')
var user = mongoose.model('users',{
name:String,
email:String,
password: String,
phone:Number,
_enabled:Boolean
});
var new_user = new user({
name:req.body.name,
email: req.body.email,
password: req.body.password,
phone: req.body.phone,
_enabled:false
});
new_user.save(function(err){
if(err) console.log(err);
});
Whenever I'm trying to run check.js, I'm getting this error
Cannot overwrite 'users' model once compiled.
I understand that this error comes due to mismatching of Schema, but I cannot see where this is happening ? I'm pretty new to mongoose and nodeJS.
Here is what I'm getting from the client interface of my MongoDB:
MongoDB shell version: 2.4.6 connecting to: test
> use event-db
switched to db event-db
> db.users.find()
{ "_id" : ObjectId("52457d8718f83293205aaa95"),
"name" : "MyName",
"email" : "myemail#me.com",
"password" : "myPassword",
"phone" : 900001123,
"_enable" : true
}
>
Another reason you might get this error is if you use the same model in different files but your require path has a different case.
For example, in my situation I had require('./models/User') in one file, and then in another file where I needed access to the User model, I had require('./models/user').
I guess the lookup for modules & mongoose is treating it as a different file. Once I made sure the case matched in both it was no longer an issue.
The error is occurring because you already have a schema defined, and then you are defining the schema again. Generally what you should do is instantiate the schema once, and then have a global object call it when it needs it.
For example:
user_model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name:String,
email:String,
password:String,
phone:Number,
_enabled:Boolean
});
module.exports = mongoose.model('users', userSchema);
check.js
var mongoose = require('mongoose');
var User = require('./user_model.js');
var db = mongoose.createConnection('localhost', 'event-db');
db.on('error', console.error.bind(console, 'connection error:'));
var a1= db.once('open',function(){
User.find({},{},function (err, users) {
mongoose.connection.close();
console.log("Username supplied"+username);
//doSomethingHere
})
});
insert.js
var mongoose = require('mongoose');
var User = require('./user_model.js');
mongoose.connect('mongodb://localhost/event-db');
var new_user = new User({
name:req.body.name
, email: req.body.email
, password: req.body.password
, phone: req.body.phone
, _enabled:false
});
new_user.save(function(err){
if(err) console.log(err);
});
I had this issue while 'watching' tests.
When the tests were edited, the watch re-ran the tests, but they failed due to this very reason.
I fixed it by checking if the model exists then use it, else create it.
import mongoose from 'mongoose';
import user from './schemas/user';
export const User = mongoose.models.User || mongoose.model('User', user);
I had this issue while unit testing.
The first time you call the model creation function, mongoose stores the model under the key you provide (e.g. 'users'). If you call the model creation function with the same key more than once, mongoose won't let you overwrite the existing model.
You can check if the model already exists in mongoose with:
let users = mongoose.model('users')
This will throw an error if the model does not exist, so you can wrap it in a try/catch in order to either get the model, or create it:
let users
try {
users = mongoose.model('users')
} catch (error) {
users = mongoose.model('users', <UsersSchema...>)
}
If you are using Serverless offline and don't want to use --skipCacheInvalidation, you can very well use:
module.exports = mongoose.models.Users || mongoose.model('Users', UsersSchema);
I have been experiencing this issue & it was not because of the schema definitions but rather of serverless offline mode - I just managed to resolve it with this:
serverless offline --skipCacheInvalidation
Which is mentioned here https://github.com/dherault/serverless-offline/issues/258
Hopefully that helps someone else who is building their project on serverless and running offline mode.
If you made it here it is possible that you had the same problem i did.
My issue was that i was defining another model with the same name.
I called my gallery and my file model "File". Darn you copy and paste!
I solved this by adding
mongoose.models = {}
before the line :
mongoose.model(<MODEL_NAME>, <MODEL_SCHEMA>)
Hope it solves your problem
This happened to me when I write like this:
import User from '../myuser/User.js';
However, the true path is '../myUser/User.js'
Click here! Official example.
Most important! thing is to export like this
export default mongoose.models.Item || mongoose.model('Item', itemsSchema)
To Solve this check if the model exists before to do the creation:
if (!mongoose.models[entityDBName]) {
return mongoose.model(entityDBName, entitySchema);
}
else {
return mongoose.models[entityDBName];
}
I know there is an accepted solution but I feel that the current solution results in a lot of boilerplate just so that you can test Models. My solution is essentially to take you model and place it inside of a function resulting in returning the new Model if the Model has not been registered but returning the existing Model if it has.
function getDemo () {
// Create your Schema
const DemoSchema = new mongoose.Schema({
name: String,
email: String
}, {
collection: 'demo'
})
// Check to see if the model has been registered with mongoose
// if it exists return that model
if (mongoose.models && mongoose.models.Demo) return mongoose.models.Demo
// if no current model exists register and return new model
return mongoose.model('Demo', DemoSchema)
}
export const Demo = getDemo()
Opening and closing connections all over the place is frustrating and does not compress well.
This way if I were to require the model two different places or more specifically in my tests I would not get errors and all the correct information is being returned.
This may give a hit for some, but I got the error as well and realized that I just misspelled the user model on importing.
wrong: const User = require('./UserModel');
correct: const User = require('./userModel');
Unbelievable but consider it.
Here is one more reason why this can happen. Perhaps this can help someone else. Notice the difference, Members vs Member. They must be the same...
export default mongoose.models.Members || mongoose.model('Member', FamilySchema)
Change to:
export default mongoose.models.Member || mongoose.model('Member', FamilySchema)
What you can also do is at your export, make sure to export an existing instance if one exists.
Typescript solution:
import { Schema, Document, model, models } from 'mongoose';
const UserSchema: Schema = new Schema({
name: {
type: String
}
});
export interface IUser extends Document {
name: string
}
export default models.Users || model<IUser>('Users', UserSchema);
This problem might occur if you define 2 different schema's with same Collection name
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: String,
});
// Trying to get the existing model to avoid OverwriteModelError
module.exports = mongoose.model("user") || mongoose.model('user', userSchema);
You can easily solve this by doing
delete mongoose.connection.models['users'];
const usersSchema = mongoose.Schema({...});
export default mongoose.model('users', usersSchema);
There is another way to throw this error.
Keep in mind that the path to the model is case sensitive.
In this similar example involving the "Category" model, the error was thrown under these conditions:
1) The require statement was mentioned in two files: ..category.js and ..index.js
2) I the first, the case was correct, in the second file it was not as follows:
category.js
index.js
I solved this issue by doing this
// Created Schema - Users
// models/Users.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
export const userSchema = new Schema({
// ...
});
Then in other files
// Another file
// index.js
import { userSchema } from "../models/Users";
const conn = mongoose.createConnection(process.env.CONNECTION_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
conn.models = {};
const Users = conn.model("Users", userSchema);
const results = await Users.find({});
Better Solution
let User;
try {
User = mongoose.model("User");
} catch {
User = mongoose.model("User", userSchema);
}
I hope this helps...
I faced this issue using Next.js and TypeScript. The top answers made it such that typings would not work.
This is what works for me:
const { Schema } = mongoose
export interface IUser {
name: string
email: string
}
const UserSchema = new Schema<IUser>({
name: { type: String, required: true },
email: { type: String, required: true },
})
const UserModel = () => mongoose.model<IUser>('User', UserSchema)
export default (mongoose.models.User || UserModel()) as ReturnType<
typeof UserModel
>
I faced the same Issue with NextJS and MongoDB atlas. I had a models folder
with the model of session stored, but the problem was not that I defined the Schema twice.
Make sure the Collection is empty and does not have a previous Document
If it does, then Simply declare a Model without Schema, like this:
const Session = mongoose.model("user_session_collection")
You can delete the previous records or backup them, create the schema and then apply query on the database.
Hope it helped
Below is the full solution to similar problem when using Mongoose with Pagination in combination with Nuxt and Typescript:
import {model, models, Schema, PaginateModel, Document } from 'mongoose';
import { default as mongoosePaginate } from 'mongoose-paginate-v2';
export interface IUser extends Document {
name: string;
}
const UserSchema: Schema = new Schema({
name: String
});
UserSchema.plugin(mongoosePaginate)
interface User<T extends Document> extends PaginateModel<T> {}
const User: User<IUser> = models['User'] as User<IUser> || model<IUser>('User', UserSchema) as User<IUser>;
export default User
tsconfig.json:
{
"compilerOptions": {
"target": "ES2018",
"module": "ESNext",
"moduleResolution": "Node",
"lib": ["ESNext", "ESNext.AsyncIterable", "DOM"],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"~/*": ["./*"],
"#/*": ["./*"]
},
"types": ["#types/node", "#nuxt/types"]
},
"exclude": ["node_modules"]
}
To make pagination working you will also need to install
#types/mongoose-paginate-v2
The above solution should also deal with problems related to hot reloading with Nuxt (ServerMiddleware errors) and pagination plugin registration.
A solution that worked for me was just to check if an instance of the model exists before creating and exporting the model.
import mongoose from "mongoose";
const { Schema } = mongoose;
const mongoosePaginate = require("mongoose-paginate");
const articleSchema = new Schema({
title: String, // String is shorthand for {type: String}
summary: String,
data: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
published: { type: Boolean, default: true },
tags: [{ name: String }],
category: String,
_id: String,
});
const Post = mongoose.models.Post ? mongoose.models.Post : mongoose.model("Post",articleSchema);
export default Post;
The schema definition should be unique for a collection, it should not be more then one schema for a collection.
If you want to overwrite the existing class for different collection using typescript
then you have to inherit the existing class from different class.
export class User extends Typegoose{
#prop
username?:string
password?:string
}
export class newUser extends User{
constructor() {
super();
}
}
export const UserModel = new User ().getModelForClass(User , { schemaOptions: { collection: "collection1" } });
export const newUserModel = new newUser ().getModelForClass(newUser , { schemaOptions: { collection: "collection2" } });
I had the same problem,
reason was I defined schema an model in a JS function, they should be defined globally in a node module, not in a function.
just export like this
exports.User = mongoose.models.User || mongoose.model('User', userSchema);
ther are so many good answer but for checking we can do easier job.
i mean in most popular answer there is check.js ,our guy made it so much complicated ,i suggest:
function connectToDB() {
if (mongoose.connection.readyState === 1) {
console.log("already connected");
return;
}
mongoose.connect(
process.env.MONGODB_URL,
{
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) throw err;
console.log("DB connected");
},
);
}
readyState== 1 means connected
so does not try to connect again
so you won't get the error
i think it because of connecting while it is connected
it is another way of connecting to db
Make sure you are not using the same model name for two different schemas.
Example:
// course model
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
course: {
type: String,
required: true,
},
course_category: {
type: String,
required: true,
}
});
module.exports = mongoose.model("course", courseSchema);
// student model
const mongoose = require("mongoose");
const studentSchema = new mongoose.Schema({
first_name: {
type: String,
required: true,
},
last_name: {
type: String,
required: true,
}
});
module.exports = mongoose.model("course", studentSchema);

Koa.js, Mongo DB application not returning any results using Mongoose

I am having a problem whereas I cannot get any results returned from a collection within a MongoDB. The db exists as does the collection and querying the MongoDB collection from the Mongo CLI returns results. i always get empty results back from the find() query within my application codebase.
My application is transpiled at runtime using babel-register.
My app.js file:
import Koa from 'koa';
import path from 'path';
import bodyParser from 'koa-bodyparser';
import serve from 'koa-static';
import mongoose from 'mongoose';
import Config from '../Config.js';
global.appRoot = path.resolve(__dirname);
const app = new Koa();
mongoose.connect(Config.mongo.url);
mongoose.connection.on('connected', (response) => {
console.log(response);
});
mongoose.connection.on('error', (err) => {
console.log(err);
});
............
This works fine and the on('connected'... callback works fine and is called.
My users schema:
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
lowercase: true
},
password: {
type: String,
required:
true
},
email: {
type: String,
required: true,
unique: true
}
});
export default mongoose.model('user', UserSchema);
My routes file:
import Router from 'koa-router';
import authenticate from '../../middlewares/authenticate';
import mockCustomerService from '../../mock-services/customerService';
import AccountController from '../../controllers/accountController';
import UserModel from '../../models/UserModel';
const AccountControllerInstance = new AccountController(UserModel);
const authRouter = new Router();
/** Login function **/
authRouter.post('/login', async (ctx, next) => {
AccountControllerObject.login(ctx)
.then((response) => {
console.log(response);
});
});
As you can see I inject the user schema into the AccountControllerInstance
Account Controller class
import ApiResponse from '../models/ApiResponse.js';
import ApiMessages from '../models/ApiMessages.js';
import UserProfileModel from '../models/UserProfileModel.js';
class AccountController {
constructor(userModel, token) {
this.ApiResponse = ApiResponse;
this.ApiMessages = ApiMessages;
this.UserProfileModel = UserProfileModel;
this.userModel = userModel;
this.token = token;
}
login(ctx) {
return this.userModel.find({ email: ctx.request.body.email });
}
This controller contains the functions to login, register etc. As you can see, the user schema is put as a property of the class in the constructor.
I then use the login function to query the Mongo instance but I never get any results returned. I have checked there are correct records in the collection and made sure the query (email in this case) is exact but still no results.
Here is an example of a record in the 'users' collection on the 'degould-login' database generated by the mongo cli with a find query.
db.user.find({email: "james.alex.holman#gmail.com"})
Result:
{ "_id" : ObjectId("594a313a98e5b9f2f9dc9553"), "email" : "james.alex.holman#gmail.com", "username" : "james", "password" : "test" }
Anyone see what's happening here?
Thanks
In app.js first you will connected with mongo via mongoose then you will load all file.
In this you are not loading router and model.
And you know mongoose connection is asynchronous, so you write code in sync way for loading models and routers. For this you will use async -await pattern or callback.

Mongoose typing issue with typescript

I am building an app using mongoose and typescript. Here is a simple model I have made:
import * as callbackMongoose from 'mongoose';
var mongoose = callbackMongoose;
mongoose.Promise = global.Promise;
const Schema = mongoose.Schema;
var userSchema = new Schema({
username: String,
email: String,
hash: String
});
export default mongoose.model('User', userSchema);
It works well but I need to cast each document to any before accessing properties. I read a guide that said I could do this:
interface IUser extends mongoose.Document {
username: String;
email: String;
hash: String;
}
export default mongoose.model<IUser>('User', userSchema);
My problem is that the type mongoose doesn't seem to have the property Document. It also doesn't have the property ObjectId. When I cast mongoose to any and use these members it works just fine. It seems to be a typing issue.
I installed the mongoose typing like so:
npm install #types/mongoose --save
The typings do work for Schema and they are good for all of the other libraries I use. Is something wrong with these type definitions? Am I doing something wrong?
For TypeScript#2.0
I think you may use
npm install #types/mongoose --save
instead of:
npm install #typings/mongoose --save
This is full example:
Database.ts
import mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://admin:123456#ds149437.mlab.com:49437/samples');
export { mongoose };
UserData.ts
import { mongoose } from './../../Services/Database';
export interface UserData {
is_temporary: boolean;
is_verified: boolean;
status: boolean;
username: string;
}
export interface IUserData extends UserData, mongoose.Document, mongoose.PassportLocalDocument { };
UserModel.ts
import { IUserData } from './UserData';
import { mongoose } from './../../Services/Database';
import * as passportLocalMongoose from 'passport-local-mongoose';
import Schema = mongoose.Schema;
const UserSchema = new Schema({
username: { type: String, required: true },
password: String,
status: { type: Boolean, required: true },
is_verified: { type: Boolean, required: true },
is_temporary: { type: Boolean, required: true }
});
UserSchema.plugin(passportLocalMongoose);
var UserModel;
try {
// Throws an error if 'Name' hasn't been registered
UserModel = mongoose.model('User')
} catch (e) {
UserModel = mongoose.model<IUserData>('User', UserSchema);
}
export = UserModel;
I also full project example using typescript, node.js, mongoose & passport.js right here: https://github.com/thanhtruong0315/typescript-express-passportjs
Good luck.

Resources