mongoose的基本使用

gjincai發表於2019-02-16

開始之前,沒什麼比過一遍官方文件更有必要的了:http://mongoosejs.com/

mongoose 是啥?有啥用?
mongoose 是操作 MongoDB 的一個物件模型庫;它封裝了MongoDB對文件操作的常用處理方法(增刪改查),讓 NodeJS 操作 Mongodb 資料庫變得快捷靈活。

本文所用到的完整程式碼:原始碼

安裝 mongoose

新建目錄 s4_mongoose 和 test.js 檔案:

mkdir s4_mongoose
cd s4_mongoose
touch test.js

初始化目錄生成 package.json 並安裝 mongoose:

npm init
cnpm install mongoose --save

連線資料庫

編輯 test.js :

var mongoose = require(`mongoose`);
var db = mongoose.connect(`mongodb://127.0.0.1:27017/test`);
db.connection.on(`error`, function(error){
  console.log(`資料庫test連線失敗:` + error);
});
db.connection.on(`open`, function(){
  console.log(`資料庫test連線成功`);
});

接著先開啟一個 iTerm2 終端,開啟 mongodb 服務:

mongod

再開啟另一個 iTerm2 終端,執行 test.js:

node test.js
//成功後便會輸出:資料庫test連線成功

Schema/Model/Entity

沒有比文件更詳細的了:http://mongoosejs.com/docs/guide.html

  1. Schema:資料庫集合的結構物件。

  2. Model :由Schema構造而成,可運算元據庫。

  3. Entity:由Model建立的實體,可運算元據庫。

看完文件後,再看看下面一段程式碼配合理解一下:

var mongoose = require("mongoose");
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
// var testModel = db.model(`test1`, testSchema); // 集合名稱;集合的結構物件
var TestSchema = new mongoose.Schema({
    name : { type:String },
    age  : { type:Number, default:0 },
    email: { type:String },
    time : { type:Date, default:Date.now }
});
var TestModel = db.model("test1", TestSchema );
var TestEntity = new TestModel({
    name : "helloworld",
    age  : 28,
    email: "helloworld@qq.com"
});
TestEntity.save(function(error,doc){
  if(error){
     console.log("error :" + error);
  }else{
     console.log(doc);
  }
});

model 資料插入

在前面的資料庫連線成功的前提下,我們在資料庫 test 下新建一個集合 test1 、並往裡面插入儲存一組資料:

var testSchema = new mongoose.Schema({
  name: {type: String},
  age: {type: Number, default: 0},
  email: {type: String},
  time: {type: Date, default: Date.now}
});
var testModel = db.model(`test1`, testSchema); // 集合名稱;集合的結構物件
// Document文件(關聯陣列式的物件) < Collection集合 < 資料庫
// 插入儲存一段資料
testModel.create([
  {name: "test1", age: 8},
  {name: "test2", age: 18},
  {name: "test3", age: 28},
  {name: "test4", age: 38},
  {name: "test5", age: 48},
  {name: "test6", age: 58, email:"tttt@qq.com"},
  {name: "test7", age: 68, email:"ssss@qq.com"},
  {name: "test8", age: 18},
  {name: "test9", age: 18, email:"rrrr@qq.com"},
  {name: "test10",age: 18}
], function (error, docs) {
  if(error) {
    console.log(error);
  } else {
    console.log(`save ok`);
    console.log(docs);
  }
});

find 資料查詢

mongoose 提供了find、findOne、和findById方法用於文件查詢。
基本語法:

model.find(Conditions,fields,options,callback(err, doc));

Conditions: 查詢條件
fields: 返回的欄位
options: 遊標(sort,limit)
callback: 回撥函式,引數doc為查詢出來的結果

條件查詢的基礎:
$lt (小於<)
$lte (小於等於<=)
$gt (大於>)
$gte (大於等於>=)
$ne (不等於,不包含!=)
$in (包含)
$or (查詢多個鍵值的任意給定值)
$exists (判斷某些屬性是否存在)
$all (全部)

具體的一些例項,程式碼裡已有詳細註釋:

// find(Conditions,fields,callback);
// 省略或為空、返回所有記錄;只包含name,age欄位,去掉預設的_id欄位;執行回撥函式
testModel.find({}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log(`查詢出錯:` + err);
  } else {
    console.log(`{}查詢結果為:`);
    console.log(docs);
  }
});
// 查詢age大於等於28,小於等於48
testModel.find({age: {$gte: 28, $lte: 48}}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log(`查詢出錯:` + err);
  } else {
    console.log(`$gte,$lte查詢結果為:`);
    console.log(docs);
  }
});
// 查詢age為58、68的2條資料
testModel.find({age: {$in: [58, 68]}}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log(`查詢出錯:` + err);
  } else {
    console.log(`$in查詢結果為:`);
    console.log(docs);
  }
});
// 查詢name為test3、或者age為18的全部資料
testModel.find({$or: [{name: `test3`}, {age: 18}]}, {name:1, age:1, _id:0}, function(err, docs){
  if (err) {
    console.log(`查詢出錯:` + err);
  } else {
    console.log(`$or查詢結果為:`);
    console.log(docs);
  }
});

// step3:遊標查詢
// 查詢name為test3、或者age為18的全部資料;但限制只查詢2條資料
testModel.find({$or: [{name: `test3`}, {age: 18}]}, {name:1, age:1, _id:0}, {limit: 2}, function(err, docs){
  if (err) {
    console.log(`查詢出錯:` + err);
  } else {
    console.log(`limit查詢結果為:`);
    console.log(docs);
  }
});

update 資料更新

基本使用:model.update(查詢條件,更新物件,callback);

var conditions = {name: `test1`};
var update = {$set: {age: 11 }};
testModel.update(conditions, update, function(error){
  if(error) {
    console.log(error);
  } else {
    console.log(`Update success!`);
    testModel.find({name: `test1`}, {name:1, age:1, _id:0}, function(err, docs){
      if (err) {
        console.log(`查詢出錯:` + err);
      } else {
        console.log(`更新test1後的查詢結果為:`);
        console.log(docs);  // 更新test_update後的查詢結果為空陣列:[ ];
                            // 更新test1後的查詢結果為: [ { name: `test1`, age: 11 } ]
                            // 只能更新本來已存在的資料
      }
    });
  }
});

remove 資料刪除

基本使用:model.remove(查詢條件,callback);

var conditions = {name: `test2`};
testModel.remove(conditions, function(error){
  if(error) {
    console.log(error);
  } else {
    console.log(`Delete success!`);
    testModel.find({name: `test2`}, {name:1, age:1, _id:0}, function(err, docs){
      if (err) {
        console.log(`查詢出錯:` + err);
      } else {
        console.log(`刪除test2後的查詢結果為:`);
        console.log(docs);  // 刪除test2後的查詢結果為空陣列:[ ];
      }
    });
  }
});

robomongo mongodb視覺化工具

安裝 mongodb 視覺化工具 robomongo
在 iTerm2 開啟本地mongodb後(執行mongod),開啟 robomongo,新建 connection 即可連上本地的 mongodb 資料庫。

相關文章