本篇文章主要介紹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); } })