認識mongoose
- Mongoose是什么衅斩?
Mongoose是MongoDB的一個對象模型工具盆顾,是基于node-mongodb-native開發(fā)的MongoDB nodejs驅動,可以在異步的環(huán)境下執(zhí)行畏梆。同時它也是針對MongoDB操作的一個對象模型庫您宪,封裝了MongoDB對文檔的的一些增刪改查等常用方法,讓NodeJS操作Mongodb數(shù)據(jù)庫變得更加靈活簡單奠涌。 - Mongoose能做什么宪巨?
Mongoose,因為封裝了對MongoDB對文檔操作的常用處理方法溜畅,讓NodeJS操作Mongodb數(shù)據(jù)庫變得easy捏卓、easy、So easy! - 數(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ù)庫連接成功怠晴!------");
});
- Schema 用來定義數(shù)據(jù)類型的工具
var mongoose = require("mongoose");
var TestSchema = new mongoose.Schema({
name : { type:String },//屬性name,類型為String
age : { type:Number, default:0 },//屬性age,類型為Number,默認為0
time : { type:Date, default:Date.now },
email: { type:String,default:''}
});
- model 數(shù)據(jù)模型
var db = mongoose.connect("mongodb://127.0.0.1:27017/test");
// 創(chuàng)建Model
var TestModel = db.model("test1", TestSchema);
- Entity 實體
var TestEntity = new TestModel({
name : "Lenka",
age : 36,
email: "lenka@qq.com"
});
console.log(TestEntity.name); // Lenka
console.log(TestEntity.age); // 36
小結
Schema:數(shù)據(jù)庫集合的模型骨架,或者是數(shù)據(jù)屬性模型傳統(tǒng)意義的表結構浴捆。
Model :通過Schema構造而成蒜田,除了具有Schema定義的數(shù)據(jù)庫骨架以外,還可以具體的操作數(shù)據(jù)庫选泻。
Entity:通過Model創(chuàng)建的實體冲粤,它也可以操作數(shù)據(jù)庫。
數(shù)據(jù)增刪改查
- find查詢
Model.find({},function(error,docs){
//若沒有向find傳遞參數(shù)页眯,默認的是顯示所有文檔
});
Model.find({ "age": 28 }, function (error, docs) {
if(error){
console.log("error :" + error);
}else{
console.log(docs); //docs: age為28的所有文檔
}
});
- Model保存
Model.create({ name:"model_create", age:26}, function(error,doc){
if(error) {
console.log(error);
} else {
console.log(doc);
}
});
- entity保存方法
var Entity = new Model({name:"entity_save",age: 27});
Entity.save(function(error,doc) {
if(error) {
console.log(error);
} else {
console.log(doc);
}
});
- 數(shù)據(jù)更新
obj.update(查詢條件,更新對象,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!');
}
});
- 刪除數(shù)據(jù)
obj.remove(查詢條件,callback);
var conditions = { name: 'tom' };
TestModel.remove(conditions, function(error){
if(error) {
console.log(error);
} else {
console.log('Delete success!');
}
});
總結
- 查詢:find查詢返回符合條件一個梯捕、多個或者空數(shù)組文檔結果。
- 保存:model調用create方法餐茵,entity調用的save方法科阎。
- 更新:obj.update(查詢條件,更新對象,callback),根據(jù)條件更新相關數(shù)據(jù)忿族。
- 刪除:obj.remove(查詢條件,callback)锣笨,根據(jù)條件刪除相關數(shù)據(jù)。
簡單查詢
- find 過濾查詢
屬性過濾 find(Conditions,field,callback);
field省略或為Null道批,則返回所有屬性错英。
//返回只包含一個鍵值name、age的所有記錄
Model.find({},{name:1, age:1, _id:0}隆豹,function(err,docs){
//docs 查詢結果集
})
- findOne的基本用法
單條數(shù)據(jù) findOne(Conditions,callback);
與find相同椭岩,但只返回單個文檔,也就說當查詢到即一個符合條件的數(shù)據(jù)時,將停止繼續(xù)查詢判哥,并返回查詢結果献雅。
TestModel.findOne({ age: 27}, function (err, doc){
// 查詢符合age等于27的第一條數(shù)據(jù)
// doc是查詢結果
});
- findById的基本用法
單條數(shù)據(jù) findById(_id, callback);
與findOne相同,但它只接收文檔的_id作為參數(shù)塌计,返回單個文檔挺身。
TestModel.findById('obj._id', function (err, doc){
//doc 查詢結果文檔
});
總結
- find過濾查詢 :find查詢時我們可以過濾返回結果所顯示的屬性個數(shù)。
- findOne查詢 :只返回符合條件的首條文檔數(shù)據(jù)锌仅。
- findById查詢:根據(jù)文檔_id來查詢文檔章钾。
高級查詢
-
lt
lt(<)贱傀、
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ù)
});
-
ne(!=)操作符的含義相當于不等于伊脓、不包含府寒,查詢時我們可通過它進行條件判定,具體使用方法如下:
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ù)
});
-
ne操作符相反椰棘,$in相當于包含、等于榄笙,查詢時查找包含于指定字段條件的數(shù)據(jù)。具體使用方法如下:
Model.find({ age:{ $in: 20}},function(error,docs){
//查詢age等于20的所有數(shù)據(jù)
});
Model.find({ age:{$in:[20,30]}},function(error,docs){
//可以把多個值組織成一個數(shù)組
});
-
or操作符祷蝌,可以查詢多個鍵值的任意給定值茅撞,只要滿足其中一個就可返回,用于存在多個條件判定的情況下使用巨朦,如下示例:
Model.find({"$or":[{"name":"yaya"},{"age":28}]},function(error,docs){
//查詢name為yaya或age為28的全部文檔
});
-
exists操作符米丘,可用于判斷某些關鍵字段是否存在來進行條件查詢。如下示例:
Model.find({name: {$exists: true}},function(error,docs){
//查詢所有存在name屬性的文檔
});
Model.find({telephone: {$exists: false}},function(error,docs){
//查詢所有不存在telephone屬性的文檔
});
總結
* $gt(>),$lt(<),$lte(<=),$gte(>=)操作符:針對Number類型的查詢具體超強的排除性糊啡。
* $ne(!=)操作符:相當于不等于拄查、不包含,查詢時可根據(jù)單個或多個屬性進行結果排除棚蓄。
* $in操作符:和$ne操作符用法相同堕扶,但意義相反。
* $or操作符:可查詢多個條件梭依,只要滿足其中一個就可返回結果值稍算。
* $exists操作符:主要用于判斷某些屬性是否存在。
游標
- 限制數(shù)量:find(Conditions,fields,options,callback);
Model.find({},null,{limit:20},function(err,docs){
console.log(docs);
});
- 跳過數(shù)量:find(Conditions,fields,options,callback);
Model.find({},null,{skip:4},function(err,docs){
console.log(docs);
});
- 結果排序:find(Conditions,fields,options,callback);
Model.find({},null,{sort:{age:-1}},function(err,docs){
//查詢所有數(shù)據(jù)役拴,并按照age降序順序返回數(shù)據(jù)docs
});
總結
- limit函數(shù):限制返回結果的數(shù)量糊探。
- skip函數(shù):略過指定的返回結果數(shù)量。
- sort函數(shù):對返回結果進行有效排序。
Mongoose 屬性方法
- Schema添加屬性值
var mongoose = require('mongoose');
var TempSchema = new mongoose.Schema;
TempSchema.add({ name: 'String', email: 'String', age: 'Number' });
- 實例方法
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
- 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的文檔結果集
});
- 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