0
votes

Hello I try rewriting my code from simple js to typescript and have some problems with mongoose schemas...

/// <reference path="../typings/tsd.d.ts" />
import * as mongoose from 'mongoose';
import * as bcrypt from "bcrypt";

var SALT_WORK_FACTOR = 10;
var mongodbURL = 'mongodb://localhost/test';
var mongodbOptions = {};

mongoose.connect(mongodbURL, mongodbOptions);

var Schema = mongoose.Schema;

// User schema
var User = new Schema({
    username: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    is_admin: { type: Boolean, default: false },
    created: { type: Date, default: Date.now }
});

// Bcrypt middleware on UserSchema
User.pre('save', function(next) {
    var user = this;

    if (!user.isModified('password')) return next();

    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err);
            user.password = hash;
            next();
        });
    });
});

//Password verification
User.methods.comparePassword = function(password, cb) {
    bcrypt.compare(password, this.password, function(err, isMatch) {
        if (err) return cb(err);
        cb(isMatch);
    });
};

var userModel: mongoose.Model<any> = mongoose.model("User", User);

//Define Models

// Export Models trying ALL WAYS (((((

declare var exports: any;
exports.userModel = userModel;

(module).exports = userModel;

exports = {
    userModel: userModel
} 

export = userModel;  // EXPORT

but when I compile *.ts amd import this file i see:

import {userModel} from '../config/mongo_database';

has no exported member 'userModel'.

OR

import db = require('../config/mongo_database');

Property 'userModel' does not exist on type 'Model'

but console.log(db) show me

{ userModel: 
   { [Function: model]
     base: 
      { connections: [Object],
        plugins: [],
        models: [Object],
        modelSchemas: [Object],
        options: [Object] },
     modelName: 'User',
     model: [Function: model],

............

is there any methods which do not use TS combo (interface,class,schema,export) and simply uses mongoose schemas? )

P.S. sorry for my english..

1

1 Answers

1
votes

1.Remove codes after // Define Models. Replace var userModel: mongoose.Model<any> = mongoose.model("User", User); with export var userModel: mongoose.Model<any> = mongoose.model("User", User); And then you can use import it with import {userModel} from '../config/mongo_database';.

2.Typescript doesn't know your model at compile time unless you provide an interface:

interface IUser{
  username: string;
  password: string;
  // ...
}
export const UserModel = mongoose.model < IUser >("User", User);