user5505266 user5505266 - 9 days ago 6
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
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?

Answer

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.