本篇文章主要介绍mongoose的一些常用api。
安装数据库连接中间件npm install mongoose -s
进入mongodb安装目录,找到bin文件夹执行命令
> mongod --dbpath=项目的db路径 注:每次重新连接之前,需要把 .lock文件删掉
可以去官网下载mongodb可视化的操作工具,操作数据库
https://robomongo.org/download
首先,我们还是需要搭建node + express架构
// 构建express服务器var express = require('express');var server = express();// 采用Promise,判断,先连接数据库成功后启动服务器。new Promise((resolve,reject)=>{//连接mongodbvar 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文件handleDB
var mongoose = require('mongoose');//定义表字段以及字段类型var userSchema = ({ username:String, password:String, age:Number, sex:{ type:String, default:'女' }})
// 表的名字 userconst UserModel = mongoose.model('user',userSchema);
插入一条数据
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('数据保存失败'); }});
组装条件查询
//按照条件查询,使用whereUserModel.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操作
/修改操作,修改查询到的第一个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); }})