mongoose常用操作

認(rèn)識(shí)mongoose

  1. Mongoose是什么?
    Mongoose是MongoDB的一個(gè)對(duì)象模型工具,是基于node-mongodb-native開發(fā)的MongoDB nodejs驅(qū)動(dòng),可以在異步的環(huán)境下執(zhí)行。同時(shí)它也是針對(duì)MongoDB操作的一個(gè)對(duì)象模型庫,封裝了MongoDB對(duì)文檔的的一些增刪改查等常用方法,讓NodeJS操作Mongodb數(shù)據(jù)庫變得更加靈活簡單。
  2. Mongoose能做什么?
    Mongoose,因?yàn)榉庋b了對(duì)MongoDB對(duì)文檔操作的常用處理方法,讓NodeJS操作Mongodb數(shù)據(jù)庫變得easy、easy、So easy!
  3. 數(shù)據(jù)庫連接
var mongoose = require("mongoose");
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
db.connection.on("error", function (error) {
    console.log("數(shù)據(jù)庫連接失?。? + error);
});
db.connection.on("open", function () {
    console.log("------數(shù)據(jù)庫連接成功!------");
});
  1. Schema 用來定義數(shù)據(jù)類型的工具
var mongoose = require("mongoose");
var TestSchema = new mongoose.Schema({
    name : { type:String },//屬性name,類型為String
    age  : { type:Number, default:0 },//屬性age,類型為Number,默認(rèn)為0
    time : { type:Date, default:Date.now },
    email: { type:String,default:''}
});
  1. model 數(shù)據(jù)模型
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
// 創(chuàng)建Model
var TestModel = db.model("test1", TestSchema);
  1. Entity 實(shí)體
var TestEntity = new TestModel({
       name : "Lenka",
       age  : 36,
       email: "lenka@qq.com"
});
console.log(TestEntity.name); // Lenka
console.log(TestEntity.age); // 36

小結(jié)

Schema:數(shù)據(jù)庫集合的模型骨架,或者是數(shù)據(jù)屬性模型傳統(tǒng)意義的表結(jié)構(gòu)。

Model :通過Schema構(gòu)造而成,除了具有Schema定義的數(shù)據(jù)庫骨架以外,還可以具體的操作數(shù)據(jù)庫。

Entity:通過Model創(chuàng)建的實(shí)體,它也可以操作數(shù)據(jù)庫。

數(shù)據(jù)增刪改查

  1. find查詢
Model.find({},function(error,docs){
   //若沒有向find傳遞參數(shù),默認(rèn)的是顯示所有文檔
});
 
Model.find({ "age": 28 }, function (error, docs) {
  if(error){
    console.log("error :" + error);
  }else{
    console.log(docs); //docs: age為28的所有文檔
  }
}); 
  1. Model保存
Model.create({ name:"model_create", age:26}, function(error,doc){
    if(error) {
        console.log(error);
    } else {
        console.log(doc);
    }
});
  1. entity保存方法
var Entity = new Model({name:"entity_save",age: 27});
 
Entity.save(function(error,doc) {
    if(error) {
        console.log(error);
    } else {
        console.log(doc);
    }
});
  1. 數(shù)據(jù)更新
    obj.update(查詢條件,更新對(duì)象,callback);
var conditions = {name : 'test_update'};
 
var update = {$set : { age : 16 }};
 
TestModel.update(conditions, update, function(error){
    if(error) {
        console.log(error);
    } else {
        console.log('Update success!');
    }
});
  1. 刪除數(shù)據(jù)
    obj.remove(查詢條件,callback);
var conditions = { name: 'tom' };
 
TestModel.remove(conditions, function(error){
    if(error) {
        console.log(error);
    } else {
        console.log('Delete success!');
    }
});

總結(jié)

  • 查詢:find查詢返回符合條件一個(gè)、多個(gè)或者空數(shù)組文檔結(jié)果。
  • 保存:model調(diào)用create方法,entity調(diào)用的save方法。
  • 更新:obj.update(查詢條件,更新對(duì)象,callback),根據(jù)條件更新相關(guān)數(shù)據(jù)。
  • 刪除:obj.remove(查詢條件,callback),根據(jù)條件刪除相關(guān)數(shù)據(jù)。

簡單查詢

  1. find 過濾查詢
    屬性過濾 find(Conditions,field,callback);
    field省略或?yàn)镹ull,則返回所有屬性。
//返回只包含一個(gè)鍵值name、age的所有記錄
Model.find({},{name:1, age:1, _id:0},function(err,docs){
   //docs 查詢結(jié)果集
})
  1. findOne的基本用法
    單條數(shù)據(jù) findOne(Conditions,callback);
    與find相同,但只返回單個(gè)文檔,也就說當(dāng)查詢到即一個(gè)符合條件的數(shù)據(jù)時(shí),將停止繼續(xù)查詢,并返回查詢結(jié)果。
TestModel.findOne({ age: 27}, function (err, doc){
   // 查詢符合age等于27的第一條數(shù)據(jù)
   // doc是查詢結(jié)果
});
  1. findById的基本用法
    單條數(shù)據(jù) findById(_id, callback);
    與findOne相同,但它只接收文檔的_id作為參數(shù),返回單個(gè)文檔。
TestModel.findById('obj._id', function (err, doc){
 //doc 查詢結(jié)果文檔
});    

總結(jié)

  • find過濾查詢 :find查詢時(shí)我們可以過濾返回結(jié)果所顯示的屬性個(gè)數(shù)。
  • findOne查詢 :只返回符合條件的首條文檔數(shù)據(jù)。
  • findById查詢:根據(jù)文檔_id來查詢文檔。

高級(jí)查詢

  1. gt、lt
    gt(>)、lt(<)、lte(<=)、gte(>=)
Model.find({"age":{"$gt":18}},function(error,docs){
   //查詢所有nage大于18的數(shù)據(jù)
});
 
Model.find({"age":{"$lt":60}},function(error,docs){
   //查詢所有nage小于60的數(shù)據(jù)
});
 
Model.find({"age":{"$gt":18,"$lt":60}},function(error,docs){
   //查詢所有nage大于18小于60的數(shù)據(jù)
});
  1. nene(!=)操作符的含義相當(dāng)于不等于、不包含,查詢時(shí)我們可通過它進(jìn)行條件判定,具體使用方法如下:
Model.find({ age:{ $ne:24}},function(error,docs){
    //查詢age不等于24的所有數(shù)據(jù)
}); 
Model.find({name:{$ne:"tom"},age:{$gte:18}},function(error,docs){
  //查詢name不等于tom、age>=18的所有數(shù)據(jù)
});
  1. in 和ne操作符相反,$in相當(dāng)于包含、等于,查詢時(shí)查找包含于指定字段條件的數(shù)據(jù)。具體使用方法如下:
Model.find({ age:{ $in: 20}},function(error,docs){
   //查詢age等于20的所有數(shù)據(jù)
});
 
Model.find({ age:{$in:[20,30]}},function(error,docs){
  //可以把多個(gè)值組織成一個(gè)數(shù)組
}); 
  1. oror操作符,可以查詢多個(gè)鍵值的任意給定值,只要滿足其中一個(gè)就可返回,用于存在多個(gè)條件判定的情況下使用,如下示例:
Model.find({"$or":[{"name":"yaya"},{"age":28}]},function(error,docs){
  //查詢name為yaya或age為28的全部文檔
});
  1. existsexists操作符,可用于判斷某些關(guān)鍵字段是否存在來進(jìn)行條件查詢。如下示例:
Model.find({name: {$exists: true}},function(error,docs){
  //查詢所有存在name屬性的文檔
});
Model.find({telephone: {$exists: false}},function(error,docs){
  //查詢所有不存在telephone屬性的文檔
});

總結(jié)

* $gt(>),$lt(<),$lte(<=),$gte(>=)操作符:針對(duì)Number類型的查詢具體超強(qiáng)的排除性。
* $ne(!=)操作符:相當(dāng)于不等于、不包含,查詢時(shí)可根據(jù)單個(gè)或多個(gè)屬性進(jìn)行結(jié)果排除。
* $in操作符:和$ne操作符用法相同,但意義相反。
* $or操作符:可查詢多個(gè)條件,只要滿足其中一個(gè)就可返回結(jié)果值。
* $exists操作符:主要用于判斷某些屬性是否存在。

游標(biāo)

  1. 限制數(shù)量:find(Conditions,fields,options,callback);
Model.find({},null,{limit:20},function(err,docs){
    console.log(docs);
});
  1. 跳過數(shù)量:find(Conditions,fields,options,callback);
Model.find({},null,{skip:4},function(err,docs){
    console.log(docs);
});
  1. 結(jié)果排序:find(Conditions,fields,options,callback);
Model.find({},null,{sort:{age:-1}},function(err,docs){
  //查詢所有數(shù)據(jù),并按照age降序順序返回?cái)?shù)據(jù)docs
});

總結(jié)

  • limit函數(shù):限制返回結(jié)果的數(shù)量。
  • skip函數(shù):略過指定的返回結(jié)果數(shù)量。
  • sort函數(shù):對(duì)返回結(jié)果進(jìn)行有效排序。

Mongoose 屬性方法

  1. Schema添加屬性值
var mongoose = require('mongoose');
var TempSchema = new mongoose.Schema;
TempSchema.add({ name: 'String', email: 'String', age: 'Number' });
  1. 實(shí)例方法
var mongoose = require('mongoose');
var saySchema = new mongoose.Schema({name : String});
saySchema.method('say', function () {
  console.log('Trouble Is A Friend');
})
var say = mongoose.model('say', saySchema);
var lenka = new say();
lenka.say(); //Trouble Is A Friend
  1. Schema靜態(tài)方法
var mongoose = require("mongoose");
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
var TestSchema = new mongoose.Schema({
    name : { type:String },
    age  : { type:Number, default:0 },
    email: { type:String, default:"" },
    time : { type:Date, default:Date.now }
});
 
TestSchema.static('findByName', function (name, callback) {
    return this.find({ name: name }, callback);
});
 
var TestModel = db.model("test1", TestSchema );
TestModel.findByName('tom', function (err, docs) {
 //docs所有名字叫tom的文檔結(jié)果集
});
  1. Schema追加方法
var mongoose = require("mongoose");
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
var TestSchema = new mongoose.Schema({
    name : { type:String },
    age  : { type:Number, default:0 },
    email: { type:String, default:"" },
    time : { type:Date, default:Date.now }
});
 
TestSchema.methods.speak = function(){
  console.log('我的名字叫'+this.name);
}
 
var TestModel = db.model('test1',TestSchema);
var TestEntity = new TestModel({name:'Lenka'});
TestEntity.speak();//我的名字叫Lenka

內(nèi)容轉(zhuǎn)載自 http://www.hubwiz.com/class/543b2e7788dba02718b5a4bd

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容