简单的nodejs + mongodb CRUD

User.js

/**
 * Created by Administrator on 2015/4/22.
 */
var mongodb = require('./db'),
    BSON = require('mongodb').BSONPure;

var User = function (user) {
    this.firstName = user.firstName;
    this.lastName = user.lastName;
};
User.prototype.AddOne = function (callback) {
    var user = {
        firstName: this.firstName,
        lastName: this.lastName
    };
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);
        }
        db.collection('user', function (err, collection) {
            if (err) {
                return callback(err);
            }
            collection.insert(
                user,
                {safe: true},
                function (err, newUser) {
                    mongodb.close();
                    if (err) {
                        return callback(err);
                    }
                    callback(null, newUser[0]);
                }
            )
        });
    });
};

User.prototype.UpdateById = function (Id, callback) {
    Id = BSON.ObjectID.createFromHexString(Id);
    var user = {
        firstName: this.firstName,
        lastName: this.lastName
    };
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);
        }
        db.collection('user', function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);
            }
            collection.update(
                {_id: Id},
                user,
                {upsert: true, multi: false},
                function (err, result) {
                    mongodb.close();
                    if (err) {
                        return callback(err);
                    }
                    callback(null, result);
                }
            );
        })
    });
};

User.DeleteById = function (Id, callback) {
    if (!Id) {
        return;
    }
    Id = BSON.ObjectID.createFromHexString(Id);
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);
        }
        db.collection('user', function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);
            }
            collection.remove({_id: Id}, function (err, result) {
                mongodb.close();
                if (err) {
                    return callback(err);
                }
                return callback(null, result);
            });
        });
    });
};

User.getAll = function (callback) {
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);
        }
        db.collection('user', function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);
            }
            collection.find().toArray(function (err, docs) {
                mongodb.close();
                if (err) {
                    return callback(err);
                }
                callback(null, docs);
            });
        });
    });
};

module.exports = User;

 app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

var settings = require('./settings');
var session = require('express-session');
var MongoStroe = require('connect-mongo')(session);
app.use(session({
    resave: false,
    saveUninitialized: true,
    secret: settings.cookieSecret,
    cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},
    stroe: new MongoStroe({
        db: settings.db,
        host: settings.host,
        port: settings.port
    })
}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

//use flash
var flash = require('connect-flash');
app.use(flash());

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

routes(app);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

index.js

var User = require('../models/User');
module.exports = function (app) {

    /* GET home page. */
    app.get('/', function (req, res, next) {
        console.log('get all the data from table user');
        User.getAll(function (err, users) {
            if (err) {
                users = [];
            }
            res.render('index',
                {
                    title: 'Node CRUD',
                    users: users
                }
            );
        });
    });

    app.post('/', function (req, res) {
        var user = {};
        user.firstName = req.body.firstName;
        user.lastName = req.body.lastName;
        var newUser = new User(user);
        newUser.AddOne(function (err, user) {
            if (err) {
                return;
            }
            req.flash('success', '添加成功');
            res.redirect('/');
        });
    });

    app.post('/delete', function (req, res) {

        User.DeleteById(req.body.Id, function (err, result) {
            if (err) {
                //返回json的数据才会成功
                res.send({data: "fail"});
            }
            res.send({data: "success"});
        });
        //User.UpdateById(1,function(err,result){
        //    if(err){
        //        console.log('update err:' + err);
        //    }
        //    console.log('update'+result);
        //});
    });
};

settings.js

/**
 * Created by Administrator on 2015/4/22.
 */
module.exports = {
    cookieSecret: 'NodeCrud',
    db: 'NodeCrud',
    host: 'localhost',
    port: '27017'
}

 db.js

/**
 * Created by Administrator on 2015/4/22.
 */

var setting = require('../settings'),
    mongodb = require('mongodb'),
    Db = mongodb.Db,
    Connect = mongodb.Connection,
    Server = mongodb.Server;

module.exports = new Db(
    setting.db,
    new Server(setting.host, setting.port),
    {safe: true}
);

  

你可能感兴趣的:(mongodb)