使用打字稿的Mongoose输入问题

时间:2016-11-27 19:12:06

标签: node.js typescript mongoose definitelytyped

我正在使用mongoose和typescript构建应用程序。这是我制作的一个简单模型:

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);

它运行良好但我需要在访问属性之前将每个文档转换为任何文档。我读了一个说我可以这样做的指南:

interface IUser extends mongoose.Document {
  username: String;
  email: String;
  hash: String;
}

export default mongoose.model<IUser>('User', userSchema);

我的问题是类型mongoose似乎没有属性Document。它也没有属性ObjectId。当我把猫鼬投到任何人并使用这些成员时它工作得很好。这似乎是打字问题。

我安装了像这样的猫鼬类型:

npm install @types/mongoose --save

这些类型适用于Schema,它们适用于我使用的所有其他库。这些类型定义有问题吗?我做错了吗?

1 个答案:

答案 0 :(得分:3)

对于TypeScript@2.0 我想你可以用

npm install @types/mongoose --save

而不是:

npm install @typings/mongoose --save

这是完整的例子:

<强> 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;

我也使用typescript,node.js,mongoose&amp; amp; passport.js就在这里:https://github.com/thanhtruong0315/typescript-express-passportjs

祝你好运。