1. 连接Mongodb数据库
npm 安装 mongodb 驱动,本地安装 mongodb 数据库
connect方法可自动检测 mongodb 连接错误,并自动重连
import { Db, MongoClient } from 'mongodb'
let client: MongoClient
let database: Db
export const connect = async(interval = 2000) => {
client = new MongoClient('mongodb://127.0.0.1/eivp')
try {
await client.connect()
database = client.db()
client.once('serverHeartbeatFailed', (e) => {
console.log('Database connect error will reconnect again')
setTimeout(connect, interval)
})
console.log('Database connected')
} catch(e) {
console.log('Database connect err will reconnect again')
setTimeout(connect, interval)
}
}
2. Where 条件查询
find 方法可指定查询条件,比如查找 group 是 admin 的 task
const collection = database.collection(name)
const list = await collection.find<Task>({ group: 'admin' })
3. Select 字段
project 方法中可指定选择或者排除哪些字段,0 代表排除,比如排除 content
const collection = database.collection(name)
const list = await collection
.find<Task>({ group: 'admin' })
.project<Task>({content:0})
.toArray()
查询语句不支持返回字段同时含有0和1,即不能同时指定排除与包含的字段,否则显示如下错误:
Cannot do inclusion on field score in exclusion projection
4. Order by 排序
在 find 可指定排序字段,比如按 ctime 降序排列
const collection = database.collection(name)
const list = await collection
.find<Task>(findOption, { sort: [[ 'ctime', -1 ]] })
.project<Task>({schema:0})
.toArray()