1 var mongoose = require('mongoose') 2 3 var Schema = mongoose.Schema 4 5 // 1. 鏈接數據庫 6 // 指定鏈接的數據庫不須要存在,當你插入第一條數據以後就會自動被建立出來 7 mongoose.connect('mongodb://localhost/itcast') 8 9 // 2. 設計文檔結構(表結構) 10 // 字段名稱就是表結構中的屬性名稱 11 // 約束的目的是爲了保證數據的完整性,不要有髒數據 12 var userSchema = new Schema({ 13 14 username: { 15 type: String, 16 required: true // 必須有 17 }, 18 password: { 19 type: String, 20 required: true 21 }, 22 email: { 23 type: String 24 } 25 }) 26 27 // 3. 將文檔結構發佈爲模型 28 // mongoose.model 方法就是用來將一個架構發佈爲 model 29 // 第一個參數:傳入一個大寫名詞單數字符串用來表示你的數據庫名稱 30 // mongoose 會自動將大寫名詞的字符串生成 小寫複數 的集合名稱 31 // 例如這裏的 User 最終會變爲 users 集合名稱 32 // 第二個參數:架構 Schema 33 // 34 // 返回值:模型構造函數 35 var User = mongoose.model('User', userSchema)
1 var admin = new User({ 2 username: 'zs', 3 password: '123456', 4 email: 'admin@admin.com' 5 }) 6 7 admin.save(function (err, ret) { 8 if (err) { 9 console.log('保存失敗') 10 } else { 11 console.log('保存成功') 12 console.log(ret) 13 } 14 })
1 // 查詢所有數據 2 User.find(function (err, ret) { 3 if (err) { 4 console.log('查詢失敗') 5 } else { 6 console.log(ret) 7 } 8 }) 9 //按條件查詢 10 User.find({ 11 username: 'zs' 12 }, function (err, ret) { 13 if (err) { 14 console.log('查詢失敗') 15 } else { 16 console.log(ret) 17 } 18 }) 19 20 //只找匹配的第一個 沒有條件會查詢第一個插入的數據 21 User.findOne({ 22 username: 'zs' 23 }, function (err, ret) { 24 if (err) { 25 console.log('查詢失敗') 26 } else { 27 console.log(ret) 28 } 29 })
1 // 根據ID修改 2 User.findByIdAndUpdate('5a001b23d219eb00c8581184', { 3 password: '123' 4 }, function (err, ret) { 5 if (err) { 6 console.log('更新失敗') 7 } else { 8 console.log('更新成功') 9 } 10 })
1 //有多少'zs' 刪多少個 2 User.remove({ 3 username: 'zs' 4 }, function (err, ret) { 5 if (err) { 6 console.log('刪除失敗') 7 } else { 8 console.log('刪除成功') 9 console.log(ret) 10 } 11 })