Mongoose索引、內置方法、靜態方法與實例方法

1. Mongoose 索引

索引是對數據庫表中一列或多列的值進行排序的一種結構,可以讓我們查詢數據庫變得更快,MongoDB 的索引幾乎與傳統的關係型數據庫一模一樣,這其中也包括一些基本的查詢優化技巧。

Mongoose 中除了以前創建索引的方式,也可以在定義 Schema 的時候指定創建索引。
// 定義schema時添加索引
var UserSchema=mongoose.Schema({
    name:{
        type:String,
        // 普通索引
        index:true     
    },
    sn:{
        type:String,
        // 唯一索引
        unique:true
    },
    age:Number,       
    status:{
        type:Number,
        default:1
    }
})

 

2. Mongoose 的內置方法

https://mongoosejs.com/docs/queries.html

1. Model.find()
 
2. Model.findById()
 
3. Model.findByIdAndDelete()
 
4. Model.findByIdAndRemove()
 
6. Model.findByIdAndUpdate()
 
7. Model.findOne()
 
8. Model.findOneAndDelete()
 
9. Model.findOneAndRemove()
 
10. Model.findOneAndUpdate()
 
11. Model.updateMany()
 
12. Model.updateOne()
 
13. Model.deleteMany()
 
14. Model.deleteOne()
 
15. Model.replaceOne()
 
 

3. Mongoose 的靜態方法與實例方法

爲 schema 添加靜態方法時通過statics關鍵字添加,添加實例方法通過methods 關鍵字添加。

// 引入自定義的連接數據庫文件
var mongoose=require('./db.js');
// 定義schema時添加索引
var UserSchema=mongoose.Schema({
    name:{
        type:String,
        // 普通索引
        index:true     
    },
    sn:{
        type:String,
        // 唯一索引
        unique:true
    },
    age:Number,       
    status:{
        type:Number,
        default:1
    }
})
// 添加一個按 sn 查找數據的靜態方法 
UserSchema.statics.findBySn=function(sn,cb){  
    // this 指向當前的 model
    this.find({"sn":sn},function(err,docs){
        cb(err,docs)
    })   
}
// 實例方法 (基本沒啥用)
UserSchema.methods.print=function(){
    console.log(this.name)
}

module.exports=mongoose.model('User',UserSchema,'user');

頁面使用時

// 引入定義模型文件
var UserModel=require('./model/user.js');
UserModel.findBySn('123456',function(err,docs){
    if(err){
        console.log(err);
        return;
    }
    console.log(docs);
    // 按sn所查找到的數據
});

var user = new UserModel({
    name: '趙六',
    sn:'12345678',
    age: 29
});

user.print();  
// 趙六

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章