1.安裝
打開命令行
npm i mongoose
2.連接數據庫
// 引入安裝的包 var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/mongoo'); //mongoo這里是代表數據庫的名稱 var db = mongoose.connection; db.on('error', console.error.bind(console, '連接失敗')); db.once('open', function() { console.log('連接成功') }); // new一個schema:把一個本身非結構化的數據變成結構化 var kittySchema = new mongoose.Schema({ name: String, age:Number, gender:String }); // 根據schema得到一個model,這個model是一個class var Kitten = mongoose.model('Kitten', kittySchema);
3.增加數據
var felyne = new Kitten({ name: '王富貴',age:18,gender:'男' }); felyne.save(function (err, res) { //回調第一個參數代表出錯 if (err) return console.error(err); //第二個帶個成功的回調參數 console.log(res) });
添加數據的方式有兩種一種是userTest.save()需要實例化模型,另一種是user.create(data,callback(err,res))這種方式不用實例化模型。
4.刪除數據
Kitten.remove({name:"王富貴"},function(arr,res){ console.log(res) }) //執行完成出現這樣的代碼 //{ n: 1, ok: 1, deletedCount: 1 } // n:條件匹配到的數據條數 // ok: 1代表語句執行成功 // deletedCount: 被刪除的數量
此方法將刪除命令直接發送到MongoDB,不涉及Mongoose文檔。由於不涉及Mongoose文檔,因此不會執行任何中間件(掛鈎)
Kitten.deleteOne({name:"王富貴"},function(arr,res){ console.log(res) }) //此方法和remove類似,最多刪除一個文檔
此方法和remove類似,最多刪除一個文檔
Kitten.deleteMany({name:"王富貴"},function(arr,res){ console.log(res) }) //此方法和remove類似,從集合中刪除所有匹配的文檔
此方法和remove類似,從集合中刪除所有匹配的文檔
5.更新數據(改數據)
Kitten.update({name:"王富貴"},{$set:{age:26}},function(arr,res){ console.log(res) }) //update 只匹配查找到的第一條數據並進行更換
update 只匹配查找到的第一條數據並進行更換
Kitten.updateMany({name:"王多余"},{$set:{age:26}},function(arr,res){ console.log(res) }) //updateMany 匹配查找到的所有document並更改
updateMany 匹配查找到的所有document並更改
Kitten.updateOne({name:"王多余"},{$set:{age:36}},function(arr,res){ console.log(res) }) //updateOne 更新匹配的第一個文檔
findByIdAndUpdate 根據id查找然后修改
Kitten.findByIdAndUpdate(id,{name:"王多余"},{new:true},function(arr,res){ console.log(res) }) //findByIdAndUpdate 根據id查找然后修改 //第一個參數必須為id //第二個參數是需要修改的內容 //第三個參數代表返回的數據是否為更新后 true為是。默認為flast。可不寫 //回調 異步代碼
6.查找數據
Kitten.find({},function(err,res){ console.log(res) }) //查找數據庫中所有數據 Kitten.find({name:'王富貴'},function(err,res){ console.log(res) }) //查找所有名字為王富貴的數據 Kitten.findOne({name:'王富貴'},function(err,res){ console.log(res) }) //查找第一個名字為王富貴的數據 Kitten.findById({_id:'5e5b43db4464113f1843e380'},function(err,res){ console.log(res) }) //根據id查找對應的數據
查詢有三種方式find查全部符合要求,findOne查到的第一個,findById通過集合中每條數據特定的_id來查詢
查詢方式還可以特定條件來查找
//"$lt"(小於) //"$lte"(小於等於) //"$gt"(大於) //"$gte"(大於等於) //"$ne"(不等於) Kitten.find({age: {$ne: 18}},function (err,res) { console.log(res) //查找age不等於18的數據 })
范圍查找
// "$in" // "$nin" Kitten.find({age: {$nin: [20,24]}},function (err,res) { console.log(res) //查找age不為20-24之間的數據 }) // "$in"查找20-24之間的數據 // "$nin"查找不為20-24之間的數據
or
Kitten.find({$or: [{name:'老王'},{name:'王富貴'}]},function (err,res) { console.log(res) //查找符合name為老王或者為王富貴的數據 })
增加數據中的save()要實例化model,其他皆可不用實例化model