博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
koa+mongoose基础入门
阅读量:6981 次
发布时间:2019-06-27

本文共 7719 字,大约阅读时间需要 25 分钟。

1.mongoose基本使用

1.安装mongodb

npm install mongodb

2.引入mongodb数据表,连接mongodb,通过node来对mongodb进行异步的增删改查

const mongodb = requrie('mongodb');mongodb.MongoClient.connect("mongodb://localhost/db1", function(err,db){    if(!err){        db.connection("col").insert({
"a": 1}), function(err, res){ if(!err){ console.log(result); } } }}复制代码

以上代码,在mongodb数据库中建立了db1数据库,然后建立了col集合,并插入{"a":1}文档

可以看出不是很好使用,所以使用mongoose简化操作

3.什么是mongoose

mongoose是在node.js异步环境下对mongodb进行便捷操作的对象模型工具。

有两个特点:

1.通过关系型数据库的思想来设计非关系型数据库

2.基于mongodb驱动,简化操作

mongoose有三个重要概念,分别是Schema,Model,Entity。

它们的关系是:Schema生成Model,Model创造Document,Model和Document都可对数据库操作造成影响,但Model比Document更具操作性。

4.安装mongoose和连接数据库

1.安装

npm install mongoose

2.引入mongoose

import mongoose from 'mongoose'

或者

const mongoose = require('mongoose')

3.使用connect()方法连接到mongodb数据库

1.连接到本地的db1服务器

mongoose.connect('mongodb://localhost/db1');复制代码

2.以用户名"u1",密码"123456"登录'db1'数据库

mongooge.connect('mongodb://ul:123456@localhost/db1', function(err){    if(err){        console.log('连接失败')    }else{        console.log('连接成功')    }})复制代码

3.断开连接

mongoose.disconnect()复制代码

5.一些概念

1.Schema

1.Schema主要用于定义MongoDB中集合Collection里文档document的结构

支持的类型有:String,Number,Date,Buffer(二进制),Boolean,Mixed(混合类型),ObjectId(对象ID),Array

2.新建Schema对象

import mongoose from 'mongoose';const Schema = mongoose.Schema;const mySchema = new Schema({    title: String,    comments: [{        body: String,        date: Date    }],    date: {        type: Date,        default: Date.now    }})复制代码

3._id

每一个文档document都会被mongoose添加一个不重复的_id,_id的数据类型不是字符串,而是ObjectID类型。如果在查询语句中要使用_id,则需要使用findById语句,而不能使用find或findOne语句

2.Model

1.模型Model是根据Schema编译出的构造器,同Model可以实例化出文档对象document

2.使用model()

const schema = new mongoose.Schema({    num: Number,    name: String,    size: String});const myModel = mongoose.model('myModel', schema);复制代码

3.实例化文档document

const doc1 = new myModel({size: 'small'});复制代码

4.文档保存 通过new myModel()创建的文档doc1,必须通过save()方法,才能将创建的文档保存到数据库的集合中,集合名词为模型名称的小写复数版

doc1.save(function(err, doc){    console.log(doc);})复制代码

6.常用API

model-文档操作

Model.find(query, [fields, options,] callback)

1.返回所有集合文档

忽略第一个参数,或为空对象 model.find({}, callback)

2.过滤查询

修改第二个参数,返回结果包含name,不包含age,_id默认为1

model.find({}, {'name':1,'age':0}, callback)

3.限制返回结果数量

第三个参数,游标操作limit限制返回结果数量为20个,不足20个则返回所有 model.find({}, null, {limit:20});

4.查询找到的第一个文档

model.findOne({}, callback);

5.根据_id查询

model.findById('obj_id', callback)

1.model.create(文档数据,callback)

const doc =({    title: "mongoose",    author: "chen"});blogModel.create(doc, function(err, docs){});复制代码

2.model.save([options],[options.safe],[options.validateBeforeSave],[fn])

const blogEntity = new blogModel({    title: "mongoose",    author: "chen"});blogEntity.save(function(err,docs){});复制代码

3.model.insertMany(doc(s),[options],[callback]) 将多条数据库一次性插入 blogModel.insertMany([ {title: 'mongoose1', author: 'chen1'}, {title: 'mongoose2', author: 'chen2'} ],function(err, docs){ } ])

model.update(查询条件,更新对象,可以使用mongodb的更新修改器) model.update(conditions, update, callback)

options控制选项:

safe:默认为true,安全模式

upsert:默认为false,不存在就创建新纪录

multi:默认为false,是否更新多个查询记录

runValidators:如果为true,执行Validation验证

setDefaultsOnInsert:如果upsert为true,在新建时插入文档定义的默认值

strict:以strict模式进行更新

overwrite:默认为false,禁用update-only模式,允许覆盖记录

blogModel.update({title:"mongoose"},{author:"miao"},{multi:true},function(err,docs){})复制代码

model.remove(查询条件,回调函数) model.remove(conditions, callback)

2.nuxt+koa+mongoose中的实际使用

1.首先配置数据库

server/dbs/config.js

export default{    dbs: 'mongodb://127.0.0.1:27017/student'}复制代码

2.编写数据表模型

server/dbs/models/address.js

import mongoose from 'mongoose'const Schema = mongoose.Schemaconst AddressSchema = new Schema({    user: {        type: String,        required: true    },    name: {        type: String,        required: true    },    gender: {        type: Number,        required: true    },    tel: {        type: String,        required: true    },    address: {        type: String,        required: true    },    houseNum: {        type: String,        required: true    },    type: {        type: Number    },    del: {        type: Boolean    }})export default mongoose.model('Address', AddressSchema)复制代码

3.编写接口

server/interface/address.js

import Router from 'koa-router';import Address from '../dbs/models/address';// 定义路由前缀let router = new Router({    prefix: '/address'})// 新增收货地址router.post('/add', async (ctx) => {    if(!ctx.isAuthenticated()){        ctx.body = {            code: -1,            msg: 'please login'        }    }else{        const {            name,            gender,            tel,            address,            houseNum,            type        } = ctx.request.body;        let naddress = new Address({            user: ctx.session.passport.user,            name,            gender,            tel,            address,            houseNum,            type,            del: false        })        let result = await naddress.save()        if(result){            ctx.body = {                code: 0,                msg: 'success'            }        }else{            ctx.body ={                code: -1,                msg: 'fail'            }        }    }})// 修改收货地址router.post('/edit', async (ctx) => {    if(!ctx.isAuthenticated()){        ctx.body = {            code: 1,            msg: 'please login'        }    }else{        const {            name,            gender,            tel,            address,            houseNum,            type        } = ctx.request.body;        try{            let result = await Address.update({
'_id': id},{ name, gender, tel, address, houseNum, type }) ctx.body = { code: 0, msg: result } }catch(e){ ctx.body ={ code: -1, msg: 'fail' } } }})// 删除地址// 这里没有真的删除,而是改变了del的值router.get('/del', async (ctx) => { if(!ctx.isAuthenticated()){ ctx.body = { code: 1, msg: 'please login' } }else{ let {id} = ctx.query; try{ let result = await Address.update({
'_id': id}, {
'del': true}) ctx.body = { code: 0, msg: result } }catch(e){ ctx.body = { code: -1, msg: 'fail' } } }})// 获取单个地址router.get('/getOne', async ctx => { if(!ctx.isAuthenticated()){ ctx.body = { code: -1, msg: 'please login' } }else{ let id = ctx.query.id; try { let result = await Address.findOne({
'_id': id,'del':false}) ctx.body = { code: 0, data: result } }catch(e){ ctx.body = { code: -1, data: {} } } }})// 获取该用户所有地址router.get('/getAll', async ctx => { if(!ctx.isAuthenticated()){ ctx.body = { code: -1, msg: 'please login' } }else{ try { let result = await Address.find({
'user': ctx.session.passport.user,'del':false}) ctx.body = { code: 0, data: result } }catch(e){ ctx.body = { code: -1, data: {} } } }})export default router复制代码

4.引入接口

server/index.js

import mongoose from 'mongoose'import dbConfig from './dbs/config'import address from './interface/address'// 连接数据库mongoose.connect(dbConfig.dbs, {    useNewUrlParser: true})// 引入路由app.use(address.routes()).use(address.allowedMethods())复制代码

转载地址:http://kqnpl.baihongyu.com/

你可能感兴趣的文章
SQL --update批量更新
查看>>
JavaScript学习指南之第一章Hello JavaScript!最基础的JavaScript入门
查看>>
jQuery EasyUI使用教程之根据条件更换数据网格行背景颜色
查看>>
/lib/libc.so.6: ELF file OS ABI invalid
查看>>
仿快图系统自带图片浏览器应用源码项目
查看>>
java ---Proxy
查看>>
linux基础命令 mv
查看>>
7.12 10.11-10.14
查看>>
用苦肉计感化倔老公,幸好他还爱着我
查看>>
MySQL 5.6 GTID+MHA
查看>>
Samba服务器搭建
查看>>
apple Pay
查看>>
哪凉快哪待着去
查看>>
Linux运维体系
查看>>
Keepalived高可用集群实践
查看>>
spring+mybatis+tkmapper+atomikos实现分布式事务(3)-动态切换数据源
查看>>
Lintcode91 Minimum Adjustment Cost solution 题解
查看>>
Linux -源码包安装
查看>>
Linux基本配置和系统安装
查看>>
磁盘格式化
查看>>