1.连接
db.js内容
var mongo = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/blog';
module.exports.DB = function (name, callback) {
mongo.connect(url, function (err, db) {
assert.equal(null, err);
var collection = db.collection(name);
if (typeof collection === 'undefined') {
db.createCollection(name);
collection = db.collection(name);
}
if (typeof callback === 'function') {
callback(db, collection);
}
});
};
2.增加
index.js内容
var DB = require('../models/db');
DB.DB('users',function (mdb,col) {
col.ensureIndex('name', {unique: true});
// 写入 user 文档
col.insert(newUser, {safe: true}, function(err, user) {
mdb.close();
if (err) {
req.flash('error', err);
return res.redirect('/reg');
}
//req.session.user = newUser;
req.flash('success', '注册成功');
res.redirect('/');
});
})
3.查询
index.js内容
DB.DB('guige',function (db,collection) {
collection.find({}).sort({time: -1}).toArray(function(err, docs) {
db.close();
if(err){
conole.log(err);
}
else{
console.dir(docs);
}
});
})