本篇文章主要介绍mongoose的一些经常使用api。
安装数据库链接中间件node
npm install mongoose -s
进入mongodb安装目录,找到bin文件夹执行命令mongodb
> mongod --dbpath=项目的db路径 注:每次从新链接以前,须要把 .lock文件删掉
能够去官网下载mongodb可视化的操做工具,操做数据库数据库
https://robomongo.org/download
首先,咱们仍是须要搭建node + express架构express
// 构建express服务器 var express = require('express'); var server = express(); // 采用Promise,判断,先链接数据库成功后启动服务器。 new Promise((resolve,reject)=>{ //链接mongodb var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017',(error)=>{ if(error) { console.log('数据库链接失败'); console.log(error); }else { console.log('数据库链接成功'); resolve(); } }) }).then(()=>{ server.listen(8080,'localhost',(req,res)=>{ console.log('服务器启动 @ localhost:8080'); }) // 将数据库的模型操做封装到handleDB js文件中,当服务器启动成功以后,获取db model 的数据 require('./handleDB'); })
新建js文件handleDBnpm
var mongoose = require('mongoose'); //定义表字段以及字段类型 var userSchema = ({ username:String, password:String, age:Number, sex:{ type:String, default:'女' } })
// 表的名字 user const UserModel = mongoose.model('user',userSchema);
插入一条数据api
const userModel = new UserModel({ username:"aaa", password:'223434', age:22, sex:'女' }) userModel.save().then((result)=>{ if(result) { console.log('一条数据插入成功'); console.log(result); } else { console.log('数据保存失败'); } });
组装条件查询服务器
//按照条件查询,使用where UserModel.where({ username:'aaa' }).find().then(res=>{ if(res) { console.log('--------------findWhere-------------------'); console.log(res); } }) //也能够把条件写到find({})里面,实现where一样的效果 UserModel.find({ username:'aaa' }).then(res=>{ if(res) { console.log('--------------find()-----------------------'); console.log(res); } })
根据id查询架构
UserModel.findById("5acc7d3b948dfe204475d02e").then(res=>{ if(res) { console.log("-------------------findById------------------"); console.log(res); } })
update操做mongoose
/修改操做,修改查询到的第一个 UserModel.update( //条件查询 {age:22}, {sex:'nvnvnv'} ).then(res=>{ console.log('---------------------update-----------------') console.log(res); }) UserModel.findByIdAndUpdate('5acc7d3b948dfe204475d02e',{username:'hahaaaaaaaaaaaaaaaaa'}) .then(res=>{ console.log('-----------findByIdAndUpdate-----------'); console.log(res); }) UserModel.findOneAndUpdate({username:'aaa',username:'dh'}).then(res=>{ if(res) { console.log('--------------findOneAndUpdate-----------'); console.log(res); } })
删除操做工具
UserModel.remove({username:'aaa2'}).then(res=>{ if(res) { console.log('----------remove0-------------'); console.log(res); } })