Nodejs 下用mongodb 怎么写出 c# 的感觉

本文介绍如何将Mongoose与TypeScript结合使用,通过具体的示例代码演示如何配置环境、定义Schema、创建接口以及实现数据库操作,使得开发过程更加便捷且类型安全。

mongoose 与 TS 怎么搭档。

博主早期是写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了

示例代码 github.com/vellengs/ty…

更多使用方法见 typerx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值