1. 程式人生 > 實用技巧 >eclipse專案中package顯白色,未包含在專案

eclipse專案中package顯白色,未包含在專案

指令

npm install mongoose //node需要操作資料庫依賴的第三方模組

net stop mongodb 關閉mongobd //每次開機前需要呼叫

net start mongodb 開啟mongobd

資料庫

使用mongoose.Schema建立集合規則

//引入第三方模組
const mongoose = require('mongoose')
//連線資料庫
mongoose.connect('mongodb://localhost/playground',{ useNewUrlParser: true,useUnifiedTopology: true })//相容配置
    .then(() => console.log('資料庫連線成功'))
    .
catch(() => console.log('資料庫連線失敗')); ​ //例項化mongoose.Schema建構函式,建立集合規則 const courseSchema = new mongoose.Schema({ name:String, author:String, isPublished:Boolean //是否帶有課程狀態,這些都被稱之為集合中的欄位 }) //使用規則建立集合,返回一個集合建構函式(Course) //引數1:集合名稱 //引數2:集合規則 const Course = mongoose.model('Course',courseSchema) //courses
//通過集合建構函式船艦文件,返回一個文件例項 const course = new Course({ name:"課程名稱", author:"李良榮", isPublished:false }) //儲存文件 course.save()

集合

建立集合

  1. 安裝並匯入mongoose模組,並使用mongoose.connect連線資料庫

  2. 使用new mongoose,Schema建立集合規則

  3. 使用mongoose.model建立集合物件(引數1:集合名稱,引數2:集合規則)

  4. Date.now設定預設時間

  5. mongoose驗證

    1. required:true 必傳欄位

    2. minlength/maxlength字串長度限制

    3. min/max數字大小限制

    4. enum:可列舉的選項

    5. trim去空格,default預設值

    6. validata:自定義驗證器

//例項化mongoose.Schema建構函式,建立集合規則
const courseSchema =  new mongoose.Schema({
  name:{
      //mongoose欄位驗證
      type:String,      
      //設定改欄位為必填欄位
      required:[true,'錯誤描述'],
      minlength:[2,'字串最小長度為2'],
      maxlength:[5,'字串最大長度為5'],
      trim:true
  },
   age:{
       type:Number,
       min:18,
       max:100
   },
    date:{
        type:Date,
        default:Date.now  //設定預設為當前時間 
    }
    author:{
        type:String,
        default:'李良榮',
        //列舉當前欄位可以擁有的值
        enum:{
            value:['李良榮','帥哥'],
            message:'錯誤資訊'
        }
    }
})
//使用規則建立集合,返回一個集合建構函式(Course)
//引數1:集合名稱
//引數2:集合規則
const Course = mongoose.model('Course',courseSchema) //courses

匯入集合

-d資料庫名 -c 集合名 --file 匯入的檔案

例: mongoimport -d playground -c users --file ./user.json

關聯集合

  1. 在規則中需要設定type:mongoose.Schema.Types.ObjectId,需要傳入ref關聯物件

  2. 在建立物件時,在欄位中傳入關聯物件id

  3. 通過find().populate('欄位')檢視資料

//例項化mongoose.Schema建構函式,建立集合規則
const courseSchema =  new mongoose.Schema({
  name:String,
  author:{
      //在這裡對User進行關聯
    type:mongoose.Schema.Types.ObjectId,
    ref:'User'
  },
  isPublished:Boolean   //是否帶有課程狀態,這些都被稱之為集合中的欄位
})
//建立物件時,傳入關聯ID
Course.create({name:'一本書',author: '5c09f2d9aeb04b22f846096b',isPublished:false})
//查詢時需要在find後加上populate才能將id變成資料展示出來
Course.find({name:'一本書'}).populate('author').then(res=>{
  console.log(res);
})

文件

建立文件

  1. 方式一:new 集合物件

  2. 方式二:集合物件的create方法建立

  3. 方式三:跟二一樣,為了方便可以使用promise

//通過集合建構函式建立文件,返回一個文件例項
const course = new Course({
  name:"測試",
  author:"李良榮",
  isPublished:false
})
//儲存文件,第一種方式需要儲存
course.save()
//建立文件的第二種方式
Course.create({name:'課程1',author:'李良榮',isPublished:false},(err,res)=>{
  console.log(err);
  console.log(res);
})
//建立文件的第三種方式,支援promise
Course.create({name:'課程2',author:'李良榮',isPublished:false})
      .then(res=>{
        console.log(res);
      })
      .catch(err=>{
        console.log(err);
      })


查詢文件

  1. 集合.find返回查詢到的所有文件,()裡放查詢條件

  2. 集合.findOne返回到的一條文件,

  3. $in包含 $gt大於 $lt小於

  4. find().select('name','emial','-_id')過濾查詢,新增-號刪除

  5. find().sort('age')排序(從小到大),新增-倒過來

  6. find().skip(2)跳過多少條資料 ,一般用於分頁

  7. find().limit(2)限制查詢數量一般用於分頁

  8. countDocuments({})查詢資料的總數量

  9. find().populate('author')多集合聯合查詢,查詢聯合表內的所有author資訊

//按升序查詢年齡在10-25歲之間喜歡踢足球的人的姓名
User.find({hobbies:{$in:['足球']},age:{$gt:10,$lt:25}})
    .select(['age','name','-_id']).sort('age')
    .then(res=>{
  console.log(res);
})
User.findOne({age:25}).then(res=>{
  console.log(res);
})
User.countDocuments({}).then(res=>{
   console.log(res);
})

刪除文件

  1. findOneAndDelete刪除一條文件

  2. deleteMany刪除滿足條件的所有文件,會優先執行

Course.findOneAndDelete({_id:'5e4b6a5ff66c2c3270dfb415'}).then(res=>{
  console.log(res);
})
Course.deleteMany({name:['課程1','課程2']}).then(res=>{
  console.log(res);
})

更新文件

updateOne()修改查詢到的第一個文件;引數1:修改前的值,引數2:修改後的值

updataMany()修改查詢到的所有文件

Course.updateOne({_id:6154974564987},req.body).then(res=>{
  console.log(res);
})
Course.updateMany({name:'測試2'},{name:'結果'}).then(res=>{
  console.log(res);
}) 

外掛

分頁外掛

指令:npm install mongoose-sex-page

const pagination = require('mongoose-sex-page')
//User表示集合的建構函式(User)
//page中的資料為查詢第幾頁(currentPage)
//size表示每一頁的資料(pageSize)
//dispaly表示總共顯示多少頁面,(total)
//exec表示像資料庫傳送查詢請求,不需要引數但是必填
pagination(User).page(1).size(20).display(8).exec()
module.exports = async(req,res)=>{
  const currentPage = req.query.page
  let articles = await pagination(Article).find({}).page(currentPage).size(3).display(3).populate('author').exec()
  res.send(articles) 查詢到的結果
  // res.render('admin/article',{
  //   link:'/admin/article',
  //   articles
  // })
}