成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

Express+MongoDB步步為'贏'

張春雷 / 2410人閱讀

摘要:全局安裝腳手架創(chuàng)建項(xiàng)目與是一個(gè)對(duì)象數(shù)據(jù)庫(kù),是用來(lái)存儲(chǔ)數(shù)據(jù)的存儲(chǔ)的數(shù)據(jù)格式為。三封裝數(shù)據(jù)庫(kù)的在文件下新建采用封裝對(duì)數(shù)據(jù)庫(kù)的操作,避免回調(diào)地獄,使得代碼能夠更好的被讀懂和維護(hù)。

前奏

Express 是什么?

Express 是一個(gè)基于 Node.js 平臺(tái)的極簡(jiǎn)、靈活的 web 應(yīng)用開發(fā)框架,它提供一系列強(qiáng)大的特性,幫助你創(chuàng)建各種 Web 和移動(dòng)設(shè)備應(yīng)用。

全局安裝express腳手架

$ npm install express-generator -g

創(chuàng)建express項(xiàng)目

$ express myapp
$ cd myapp
$ npm install
$ DEBUG=myapp npm start

MongoDB與Mongoose?

MongoDB是一個(gè)對(duì)象數(shù)據(jù)庫(kù),是用來(lái)存儲(chǔ)數(shù)據(jù)的;存儲(chǔ)的數(shù)據(jù)格式為JSON。

Mongoose是封裝了MongoDB操作(增刪改查等)的一個(gè)對(duì)象模型庫(kù),是用來(lái)操作這些數(shù)據(jù)的。

安裝MongoDB:
https://www.mongodb.com/download-center?jmp=nav

安裝Mongoose:

$ npm install mongoose --save
一、連接MongoDB

在項(xiàng)目根目錄下新建/lib/mongo.js

var mongoose = require("mongoose");

var db = mongoose.connect("mongodb://localhost:27017/myblog");

module.exports = db

要連接的數(shù)據(jù)庫(kù)為myblog

二、Schema

一種以文件形式存儲(chǔ)的數(shù)據(jù)庫(kù)模型骨架,無(wú)法直接通往數(shù)據(jù)庫(kù)端,不具備對(duì)數(shù)據(jù)庫(kù)的操作能力,僅僅只是數(shù)據(jù)庫(kù)模型在程序片段中的一種表現(xiàn),可以說(shuō)是數(shù)據(jù)屬性模型(傳統(tǒng)意義的表結(jié)構(gòu)),又或著是“集合”的模型骨架

新建一個(gè)用戶Schema

在項(xiàng)目根目錄下新建/models/users.js

var mongoose = require("mongoose");
var db = require("../lib/mongo");
//一個(gè)用戶模型
var UserSchema = new mongoose.Schema({
    username    : { type:String },
    password    : {type: String},
    avatar      : {type: String},
    age         : { type:Number, default:0 },
    description : { type: String},
    email       : { type: String },
    github      : { type: String },
    time        : { type:Date, default:Date.now }
});
//創(chuàng)建Model
var UserModel = db.model("user", UserSchema );
module.exports = UserModel

user:數(shù)據(jù)庫(kù)中的集合名稱,當(dāng)我們對(duì)其添加數(shù)據(jù)時(shí)如果user已經(jīng)存在,則會(huì)保存到其目錄下,如果不存在,則會(huì)創(chuàng)建user集合,然后在保存數(shù)據(jù)。

擁有了Model,我們也就擁有了操作數(shù)據(jù)庫(kù)的金鑰匙,就可以使用Model來(lái)進(jìn)行增刪改查的具體操作。

Entity

由Model創(chuàng)建的實(shí)體,使用save方法保存數(shù)據(jù),Model和Entity都有能影響數(shù)據(jù)庫(kù)的操作,但Model比Entity更具操作性。

var UserEntity = new UserModel({
    name : "hzzly",
    age  : 21,
    email: "[email protected]",
    github: "https://github.com/hzzly"
});
UserEntity.save(function(error,doc){
    if(error){
        console.log("error :" + error);
    }else{
        console.log(doc);
    }
});
三、封裝數(shù)據(jù)庫(kù)的CURD

在lib文件下新建api.js

采用Promise封裝對(duì)數(shù)據(jù)庫(kù)的操作,避免回調(diào)地獄,使得代碼能夠更好的被讀懂和維護(hù)。

var UserModel = require("../models/users");

module.exports = {
    /**
     * 添加數(shù)據(jù)
     * @param  {[type]} data 需要保存的數(shù)據(jù)對(duì)象
     */
    save(data) {
        return new Promise((resolve, reject) => {
            //model.create(保存的對(duì)象,callback)
            UserModel.create(data, (error, doc) => {
                if(error){
                    reject(error)
                }else{
                    resolve(doc)
                }
            })
        })
    },
    find(data={}, fields=null, options={}) {
        return new Promise((resolve, reject) => {
            //model.find(需要查找的對(duì)象(如果為空,則查找到所有數(shù)據(jù)), 屬性過(guò)濾對(duì)象[可選參數(shù)], options[可選參數(shù)], callback)
            UserModel.find(data, fields, options, (error, doc) => {
                if(error){
                    reject(error)
                }else{
                    resolve(doc)
                }
            })
        })
    },
    findOne(data) {
        return new Promise((resolve, reject) => {
            //model.findOne(需要查找的對(duì)象,callback)
            UserModel.findOne(data, (error, doc) => {
                if(error){
                    reject(error)
                }else{
                    resolve(doc)
                }
            })
        })
    },
    findById(data) {
        return new Promise((resolve, reject) => {
            //model.findById(需要查找的id對(duì)象 ,callback)
            UserModel.findById(data, (error, doc) => {
                if(error){
                    reject(error)
                }else{
                    resolve(doc)
                }
            })
        })
    },
    update(conditions, update) {
        return new Promise((resolve, reject) => {
            //model.update(查詢條件,更新對(duì)象,callback)
            UserModel.update(conditions, update, (error, doc) => {
                if(error){
                    reject(error)
                }else{
                    resolve(doc)
                }
            })
        })
    },
    remove(conditions) {
        return new Promise((resolve, reject) => {
            //model.update(查詢條件,callback)
            UserModel.remove(conditions, (error, doc) => {
                if(error){
                    reject(error)
                }else{
                    resolve(doc)
                }
            })
        })
    }
}
四、使用

在/routers/index.js中使用

var api = require("../lib/api");

router.post("/login", function(req, res, next) {
    var user = {
        username : req.body.username,
        password: req.body.password
    };
    api.findOne(user)
        .then(result => {
            console.log(result)
        })
})
router.post("/sign_up", function(req, res, next) {
    var user = {
        username : req.body.username,
        password: req.body.password,
        email: req.body.email
    };
    api.save(user)
        .then(result => {
            console.log(result)            
        })
})
router.get("/user_list", function(req, res, next) {
    //返回所有用戶
    api.find({})
        .then(result => {
            console.log(result)            
        })
    //返回只包含一個(gè)鍵值name、age的所有記錄
    api.find({},{name:1, age:1, _id:0})
        .then(result => {
            console.log(result)            
        })
    //返回所有age大于18的數(shù)據(jù)
    api.find({"age":{"$gt":18}})
        .then(result => {
            console.log(result)            
        })
    //返回20條數(shù)據(jù)
    api.find({},null,{limit:20})
        .then(result => {
            console.log(result)            
        })
    //查詢所有數(shù)據(jù),并按照age降序順序返回?cái)?shù)據(jù)
    api.find({},null,{sort:{age:-1}}) //1是升序,-1是降序
        .then(result => {
            console.log(result)            
        })
})

項(xiàng)目Github地址: https://github.com/hzzly/expr...
如果對(duì)你有幫助,歡迎star

文章來(lái)源hzzly博客技術(shù)分享

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/18979.html

相關(guān)文章

  • mongodb: “invalid character ',' looking

    摘要:我以為是編碼的問(wèn)題,可能是下的編碼有問(wèn)題,因?yàn)橛幸粋€(gè)談?wù)撨@個(gè)問(wèn)題的。其中遇到了也是的問(wèn)題提到的這個(gè)做法很不錯(cuò),使用這個(gè)參數(shù)確定位置。 從群里獲取了一個(gè)超大的json(也就800M),需要導(dǎo)入mongodb,然后遇到了一個(gè)問(wèn)題: $ mongoimport --db weibo --collection data --file test.json 2018-05-09T16:10:22....

    Edison 評(píng)論0 收藏0
  • mongodb: “invalid character ',' looking

    摘要:我以為是編碼的問(wèn)題,可能是下的編碼有問(wèn)題,因?yàn)橛幸粋€(gè)談?wù)撨@個(gè)問(wèn)題的。其中遇到了也是的問(wèn)題提到的這個(gè)做法很不錯(cuò),使用這個(gè)參數(shù)確定位置。 從群里獲取了一個(gè)超大的json(也就800M),需要導(dǎo)入mongodb,然后遇到了一個(gè)問(wèn)題: $ mongoimport --db weibo --collection data --file test.json 2018-05-09T16:10:22....

    Faremax 評(píng)論0 收藏0
  • The default storage engine 'wiredTiger'

    摘要:位系統(tǒng)在安裝數(shù)據(jù)庫(kù)時(shí)遇到問(wèn)題。根據(jù)錯(cuò)誤提示得知是由于當(dāng)前數(shù)據(jù)庫(kù)引擎不支持系統(tǒng)所導(dǎo)致的。解決這個(gè)問(wèn)題很簡(jiǎn)單,只要切換下的默認(rèn)數(shù)據(jù)庫(kù)引擎即可,當(dāng)然最好是升級(jí)到位系統(tǒng),畢竟沒(méi)有的限制而且新引擎的性能也有很大的提升。 win7 32位系統(tǒng)在安裝mongodb數(shù)據(jù)庫(kù)時(shí)遇到問(wèn)題。 2016-01-05T17:44:48.381+0800 I STORAGE ?[initandlisten] exc...

    Dean 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<