第4章 MongoDB入门

2016-11-02  本文已影响13人  不系流年系乾坤

BSON

BSON这种格式是专门为MongoDB而开发的,类似json的一种二进制格式。
这种格式不一定比json存储的文件小,其优点是解释快。

mongodb副本集

http://www.cnblogs.com/visionwang/p/3290435.html

mongodb分片

http://www.lanceyan.com/tech/arch/mongodb_shard1.html

mongodb操作

use

app/controllers/index.js

exports.render = function(req, res) {
    if (req.session.lastVisit) {
        console.log(req.session.lastVisit);
    }

    req.session.lastVisit = new Date();

    res.render('index', {
        title: 'Hello World'
    });
};

app/controllers/users.js

var User = require('mongoose').model('User');

exports.create = function(req, res, next) {
    var user = new User(req.body);

    user.save(function(err) {
        if (err) {
            return next(err);
        } else {
            res.jsonp(user);
        }
    });
};

exports.list = function(req, res, next) {
    User.find({}, function(err, users) {
        if (err) {
            return next(err);
        } else {
            res.jsonp(users);
        }
    });
};

exports.read = function(req, res, next) {
    res.jsonp(req.user);
};

exports.update = function(req, res, next) {
    User.findByIdAndUpdate(req.user.id, req.body, function(err, user) {
        if (err) {
            return next(err);
        } else {
            res.jsonp(user);
        }
    })
};

exports.delete = function(req, res, next) {
    req.user.remove(function(err) {
        if (err) {
            return next(err);
        } else {
            res.jsonp(req.user);
        }
    })
};

exports.userByID = function(req, res, next, id) {
    User.findOne({
        _id: id
    }, function(err, user) {
        if (err) {
            return next(err);
        } else {
            req.user = user;
            next();
        }
    });
};

app/models/user.js

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var UserSchema = new Schema({
    firstName: String,
    lastName: String,
    email: {
        type: String,
        match: /.+\@.+\..+/
    },
    username: {
        type: String,
        unique: true,
        trim: true
    },
    password: {
        type: String,
        validate: [
            function(password) {
                return password.length > 6;
            }, 'Password should longer'
        ]
    },
    website: {
        type: String,
        set: function(url) {
            if (!url) {
                return null;
            } else {
                if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) {
                    url = 'http://' + url;
                }

                return url;
            }
        }
    },
    role: {
        type: String,
        enum: ['Admin', 'Owner', 'User']
    },
    created: {
        type: Date,
        default: Date.now
    }
});


UserSchema.virtual('fullName').get(function() {
    return this.firstName + ' ' + this.lastName;
}).set(function(fullName) {
    var splitName = fullName.split(' ');
    this.firstName = splitName[0] || '';
    this.lastName = splitName[1] || '';
});

UserSchema.statics.findOneByUsername = function(username, callback) {
    this.findOne({
        username: new RegExp(username, 'i')
    }, callback);
};

UserSchema.methods.authenticate = function(password) {
    return this.password === password;
};


UserSchema.set('toJSON', {
    getters: true,
    virtuals: true
});

mongoose.model('User', UserSchema);

app/routes/index.js

module.exports = function(app) {
    var index = require('../controllers/index');
    app.get('/', index.render);
};

app/routes/users.js

var users = require('../../app/controllers/users');

module.exports = function(app) {
    app.post('/users', users.create);
    app.get('/users', users.list);
    app.get('/users/:userId', users.read);
    app.put('/users/:userId', users.update);
    app.del('/users/:userId', users.delete);

    app.param('userId', users.userByID);
};

app/views/index.ejs

config/env/development.js

module.exports = {
    db: 'mongodb://localhost/mean-book',
    sessionSecret: 'Your Application Session Secret',
    viewEngine: 'ejs'
};

config/config.js

var path = require('path');

module.exports = require(path.resolve('./config/env/' + process.env.NODE_ENV + '.js'));

config/express.js

var express = require('express'),
    config = require('./config');

module.exports = function() {
    var app = express();

    require('../app/models/user');

    app.configure(function() {
        app.use(express.logger('dev'));

        app.use(express.json());
        app.use(express.urlencoded());

        app.use(express.cookieParser());
        app.use(express.session({
            secret: config.sessionSecret
        }));

        app.set('views', __dirname + '/../app/views');
        app.set('view engine', config.viewEngine);
    });

    app.configure('production', function() {
        app.use(express.compress());
    });

    require('../app/routes/index.js')(app);
    require('../app/routes/users.js')(app);

    app.configure(function() {
        app.use(express.static(__dirname + '/../public'));
    });

    return app;
};

public

server.js

process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var mongoose = require('mongoose'),
    config = require('./config/config');

var db = mongoose.connect(config.db);

var express = require('./config/express');
var app = express();

app.listen(3000);

console.log('Server running at http://localhost:3000/');
上一篇下一篇

猜你喜欢

热点阅读