寫這篇文章是因為在寫Node中用到了mongoose中間件。以前我的認知中這就是Node Application和Mongodb用於連接的中間價。但是這篇文章之後我不在這麼認為了。如同題圖說的這是用於node.js實現優雅的mongodb建模的中間件,所以連接資料庫只是它的一部分而已。

Star Mongoose

  • 官方網址:mongoosejs.com/
  • Github:Automattic/mongoose
  • npmjs:mongoose

以上是關於mongoose的文檔

Descs

Installation

$ npm install mongoose

Use

import mongoose from mongoose

Connect Database

mongoose.connect(URL,Options)

URL:資料庫地址

Options:參數

Create Model

在我們編寫Node應用時候都會創建Model,這個Model映射著我們資料庫中的欄位以及欄位的屬性和其他的一些信息。在使用mongoose中間件的時候我們需要創建schema

const Schema = mongoose.Schema;

const User = new Schema({
username:{ type: String, required: true, unique: true },
password:{ type: String, required: true },
is_admin:{ type: Boolean, default: false },
created:{ type: Date, default: Date.now }
});

然後我們可以藉助Schema去創建Model.

Middleware

使用pre創建中間件

/**
*創建一個密碼加密的中間件
*/
User.pre(save,function (next) {

const user = this;
if(!user.isModified(password)){
return next;
}

bcrypt.genSalt(SALT_WORK_FACTOR,function (err,salt) {
if(err){
return next(err);
}

bcrypt.hash(user.password,salt,function (err,hash) {
if(err){
return next(err);
}
user.password = hash;
next();
});
});

});

pre中間件執行下一個方法的時候使用next()調用

Accessing a Model

const userModel = mongoose.model(User,User);

const userModel = mongoose.model(User);

以上是mongoose兩種訪問Module的方法。兩者的區別就是若使用第二種會使mongodb自動創建collection,而不會使用你手動創建的collection.

未完待續...

推薦閱讀:

相关文章