Reputation: 603
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?
Upvotes: 1
Views: 3227
Reputation: 1282
For [email protected] 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:[email protected]: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.
Upvotes: 4