创建猫鼬方法并将其导出

时间:2019-01-17 15:57:59

标签: typescript mongoose methods

我想创建一种方法,该方法将接收帖子的正文,并使用body.username查找用户,但是我无法访问在moongose方法中创建的方法。

user.model.ts

import * as connections from     '../../../../core/connections/mongodb.connection';
import { Schema, Document, Types } from 'mongoose';

export interface IUserModel extends Document {
    createdAt?: Date;
    updatedAt?: Date;
    username: string;
    first_name: string;
    email: string;
    password: string;
}

const UserSchema: Schema = new Schema({
    username: {
        type: String,
        required: true
    },
    first_name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
}, {
       collection: 'usermodel',
        versionKey: false
    }).pre('save', (next) => {
    // this will run before saving
    if (this._doc) {
        const doc: IUserModel = this._doc;
        const now: Date = new Date();

        if (!doc.createdAt) {
            doc.createdAt = now;
        }
        doc.updatedAt = now;
    }
    next();

    return this;
});

UserSchema.methods.findByID2 = function (body) {
    let id: any;
    this.findById({ _id: Types.ObjectId(id) }).exec((err, user) => {
        console.log(user);
    });
}


export default connections.db.model<IUserModel>('UserModel', UserSchema);

user.controller.ts

import { default as config } from '../../../../env/index';
import * as express from 'express';
import UserModel from '../models/user.model';
import IUserModel from '../models/user.model';
import EventsEmitter from '../../../../core/middleware/events-emitter/events-emitter.middleware';
import { ConnectionLib } from '../../../../core/libraries/connection/connection.lib';
import { connection, Mongoose, Types, Connection } from 'mongoose';
import { JwtLib } from '../../../../core/libraries/jwt/jwt.lib';
import * as bcrypt from 'bcrypt';

export class UserController {

public getUser(req: express.Request, res: express.Response, next: express.NextFunction): void {
    UserController.eventLogger = new EventsEmitter('User - Get User');
    UserController.eventLogger.$emit('User - Update', 'info', ['Get User running fine!']);
    IUserModel.findById({ _id: Types.ObjectId(req.params.id) }).exec((err, user) => {
      if (err) {
        res.status(500).json({
          err: err
        });
      }
      UserController.eventLogger.$emit('User - SingUP', 'info', ['Get User working fine!']);
      res.status(200).json({
        status: 'OK',
        user: user
      });
    });
  }
}

现在,我要删除IUserModel.findById并将其替换为我在用户模型中创建的findByID2。

0 个答案:

没有答案