user5505266 user5505266 - 1 year ago 181
TypeScript Question

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
. It also doesn't have the property
. 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?

Answer Source

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:


import mongoose = require('mongoose');

mongoose.Promise = global.Promise;


export { mongoose };


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 { };


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 }


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:

Good luck.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download