用Nodejs 写mongodb操作写出 C# 风

博主早期是写C# 的, 非常喜欢 linq 和 lambda 表达式的写法, 转写 node 之后原本以为同是 javascript 系的mongodb, node 下写起来应该比 c# 更舒适才对, 然而直到 typescript 相对成熟后 通过 mongoose 的 types definition 才让我真正找回感觉。

最近开源了 typerx, 所以也和大家分享下这个愉悦的写法。

初始化项目及安装模块

npm init
npm install  mongoose bluebird --save 
npm install  @types/bluebird @types/mongoose @types/node --save-dev

创建连接字符串模块 connector.ts

import * as mongoose from 'mongoose';
import bluebird from 'bluebird';

export function connect(uri: string) {
    (<any>mongoose).Promise = bluebird;
    mongoose.connect(uri);
    const db = mongoose.connection;
    db.on('error', (err: any) => {
        throw new Error('unable to connect to database at ' + uri + err);
    });
}

创建 schema

import { Schema, SchemaTypes as t, SchemaOptions, model } from 'mongoose';

export const ExampleSchema = new Schema({
    title: t.String,
    content: t.Mixed
},
    { timestamps: true });

使用 timestamps 参数可以自动维护两个时间字段

创建 interface

export class Example {
    id: string;
    title: string;
    content: string;
}

创建 database 模块

import { model, Document } from 'mongoose';
import { Example } from './interfaces/example.interface';
import { ExampleSchema } from './schemas/example.schema';

export const ModuleDatabase = {
    Example: model<Example & Document>('Example', ExampleSchema),
};

这里是类型配对的关键

创建 example.service.ts

import { ModuleDatabase as Db } from './modules/module.database';

export class ExampleService {
    async findOneByTitle(title: string) {
        return Db.Example.findOne({ title: title }).exec();
    }
}

在这里敲 Db. , Db.Example. 等都能呼出相应的类型接口,非常方便。

创建一个调用示例 test.ts

import { connect } from './connector';
import { ExampleService } from './example.service';
connect('mongodb://localhost/example');

const service = new ExampleService();
service.findOneByTitle('hello').then(res => console.log('title', res.title));

在这里敲 res. 就能呼出 title了

示例代码 https://github.com/vellengs/typerx-blogs

更多使用方法见 typerx

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 肺经自我疏理方法 一、探查部位、手法及感受 疏理手法、感受 1、自我疏理时,请掌心向上,前臂自然放松平举,肘关节屈...
    雀登梅阅读 1,089评论 0 2
  • selenium和phantomJS ——编辑:今夕何夕 目录清单 [x] . selenium和phantomj...
    風起时想妳阅读 139评论 0 0
  • [暴雪将至][HD-1080P.MP4][国语中字/1.38GB][2017大陆悬疑犯罪片] 导演: 董越 编剧:...
    FinanceMaster阅读 619评论 0 0
  • 有人说厦门是一个最令人感到温暖的地方。并说如果宠爱一个人,就带她去厦门。 毫无计划的,却在特殊的时刻来到了厦门...
    巴蜀宝贝阅读 414评论 0 1
  • “枯藤老树昏鸦”如果代表的是成熟与衰老,那么“小桥流水人家”就是青春、活力、希望了。 单纯与成熟,...
    烽火煤阅读 303评论 0 0

友情链接更多精彩内容