1. 程式人生 > 實用技巧 >雜項 ----MongoDB

雜項 ----MongoDB

database:資料庫,mongoDB資料庫軟體中可以建立多個數據庫
collection:集合,一組資料的集合,可以理解為JavaScript中的陣列
document:文件,一條具體的資料,可以理解為JavaScript中的物件
field:欄位,文件中的屬性名稱,可以理解為JavaScript中的物件屬性

一、使用
  1.啟動MongoDB
  在命令列工具中執行net start mongoDB即可啟動MongoDB,否則MongoDB將無法連線。
  匯入資料:mongoimport –d 資料庫名稱 –c 集合名稱 –file 要匯入的資料檔案


  2.資料庫連線
    mongoose.connect('mongodb://localhost/playground')
    .then(() => console.log('資料庫連線成功'))
    .catch(err => console.log('資料庫連線失敗', err));
  3.建立資料庫
    在MongoDB中如果正在使用的資料庫不存在,MongoDB會自動建立。
    --如果你建立了一個數據庫但裡面沒有資料,那麼就在mongodb compass裡看不到這個資料庫
  4.建立集合
    建立集合分為兩步,一是對對集合設定規則,二是建立集合,建立mongoose.Schema建構函式的例項即可建立集合。

1 // 設定集合規則
2 const courseSchema = new mongoose.Schema({
3     name: String,
4     author: String,
5     isPublished: Boolean
6     });
7 // 建立集合並應用規則
8 const Course = mongoose.model('Course', courseSchema); // courses

  5.建立文件


    建立文件實際上就是向集合中插入資料。
    分為兩步:
      1.建立集合例項。
      2.呼叫例項物件下的save方法將資料儲存到資料庫中。
  // 方法1:建立集合例項並插入資料

const course = new Course({
    name: 'Node.js course',
    author: '黑馬講師',
    tags: ['node', 'backend'],
    isPublished: true
    });
// 將資料儲存到資料庫中
course.save();

  //方法2.往建立的集合插入資料
  

Course.create({name: 'JavaScript基礎', author: '黑馬講師', isPublish: true}, (err, doc) => { 
// 錯誤物件
console.log(err)
// 當前插入的文件
console.log(doc)
});

  //方法3:
    

Course.create({name: 'JavaScript基礎', author: '黑馬講師', isPublish: true})
.then(doc => console.log(doc))
.catch(err => console.log(err))

  6.查詢文件
    1.// 根據條件查詢文件(條件為空則查詢所有文件)
      Course.find().then(result => console.log(result))
    2.// 根據條件查詢文件
      Course.findOne({name: 'node.js基礎'}).then(result => console.log(result))
    3.// 匹配大於 小於
      User.find({age: {$gt: 20, $lt: 50}}).then(result => console.log(result))
    4. // 匹配包含
      User.find({hobbies: {$in: ['敲程式碼']}}).then(result => console.log(result))
    5.// 選擇要查詢的欄位
      User.find().select('name email').then(result => console.log(result))
    6. // 將資料按照年齡進行排序
      User.find().sort('age').then(result => console.log(result))
    7.// skip 跳過多少條資料 limit 限制查詢數量
      User.find().skip(2).limit(2).then(result => console.log(result))

  7.刪除文件
    // 刪除單個
    Course.findOneAndDelete({}).then(result => console.log(result))
    // 刪除多個
    User.deleteMany({}).then(result => console.log(result))

  8.更新文件
    // 更新單個
    User.updateOne({查詢條件}, {要修改的值}).then(result => console.log(result))
    // 更新多個
    User.updateMany({查詢條件}, {要更改的值}).then(result => console.log(result))

  9.集合關聯實現
    // 使用者集合
      const User = mongoose.model('User', new mongoose.Schema({ name: { type: String } }));
    // 文章集合
      const Post = mongoose.model('Post', new mongoose.Schema({
      title: { type: String },
    // 使用ID將文章集合和作者集合進行關聯
      author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
      }));
    //聯合查詢
      Post.find()
      .populate('author')
      .then((err, result) => console.log(result));


  10.mongoose驗證
    在建立集合規則時,可以設定當前欄位的驗證規則,驗證失敗就則輸入插入失敗。
    獲取錯誤資訊:error.errors['欄位名稱'].message

required: true 必傳欄位
minlength:3 字串最小長度
maxlength: 20 字串最大長度
min: 2 數值最小為2
max: 100 數值最大為100
enum: ['html', 'css', 'javascript', 'node.js']
trim: true 去除字串兩邊的空格
validate: 自定義驗證器
default: 預設值

如果沒有條件就是所有(刪除,更新)


301是重定向的狀態
res.writeHead(301,{
Location:'/list'//跳轉路徑
})