如何设置Typegoose

时间:2018-11-11 01:34:55

标签: node.js mongodb typescript mongoose

如何为NodeJs REST API和打字稿设置Typegoose?

我总是收到诸如MongoParseError: Incomplete key value pair for option之类的奇怪错误消息,或者尽管有一些,但我没有收到任何数据。

有人可以提供完整的示例吗?

1 个答案:

答案 0 :(得分:0)

如果要在以下条件下编程API,可以使用下面提供的最小示例:

条件: NodeJS Typescript MongoDB (locally)

示例:

如果您使用的是打字稿,则建议使用与此类似的项目结构:

├── dist
|   ├── (your compiled JS)
├── src
|   ├── models
|   |   ├── user.model.ts
|   ├── user-repository.ts
|   ├── app.ts
|   ├── index.ts
├── test
|   ├── (your tests)

此外,还需要安装以下软件包

npm install --save typescript mongoose express @types/express @types/mongoose typegoose

index.ts:

这个文件,我只是出于引导目的

import app from './app';

const port = 3000;

app.listen(port, (err) => {
    if (err) {
        return console.log(err);
    }
    return console.log('Server up and running on ' + port);
});

app.ts:

这里,实际的逻辑还在继续

import { UserRepository } from './user-repository';
import * as express from 'express';

export class App {
    public app;

    constructor() {
        this.app = express();
        this.config();
        this.mountRoutes();
    }

    private mountRoutes() {
        // Definition of the possible API routes
        this.app.route('/users')
            .get((req, res) => {
                var repo = new UserRepository();
                // we catch the result with the typical "then"
                repo.getUsers().then((x) => {
                    // .json(x) instead of .send(x) should also be okay
                    res.status(200).send(x);
                });
            });

        //               here with parameter
        //                      |
        //                      v
        this.app.route('/users/:id')
            .get((req, res) => {
                var repo = new UserRepository();

                repo.getUser(req.params.id).then((x) => {
                    res.status(200).send(x);
            });
        });
    }
}

export default new App().app;

user-repository.ts

import * as mongoose from 'mongoose';
import { User, UserModel } from './models/user.model';


export class UserRepository {
    constructor() {
        //                protocol  host      port  database
        //                   |       |         |        |
        //                   v       v         v        v
        mongoose.connect('mongodb://localhost:27017/mongotest');
        // this only works, if your mongodb has no auth configured
        // if you need authentication, use the following:
        // mongoose.connect(MONGO_URL, {
        //     auth: {
        //         user: MONGO_DB_USER,
        //         password: MONGO_DB_PASSWORD
        //     },
        // })
    }

    async getUser(id: number): Promise<User> {
        //                  json query object as usual
        //                               |
        //                               v
        return UserModel.findOne({"userId": id});
    }

    async getUsers(): Promise<User[]> {
        return UserModel.find({});
    }
}

user.model.ts

import * as mongoose from 'mongoose';
import { prop, Typegoose } from 'typegoose';


export class User extends Typegoose{
    // properties
    // |
    // v
    @prop()
    userId: number;
    @prop()
    firstname?: string;
    @prop()
    lastname: string;
    @prop()
    email: string;
}

export const UserModel = new User().getModelForClass(User, {
    existingMongoose: mongoose,
    //  had many problems without that definition of the collection name
    //  so better define it
    //                        |
    //                        v
    schemaOptions: {collection: 'users'}
})

很明显,我有一个mongodb在本地运行,有一个名为mongotest的数据库,并且内部有一个名为users的集合。