1:先新建一個congfig文件夾:在裏面新建config.js mongoose.jsmongodb
//config.js module.exports={ //配置數據庫url mongodb:"mongodb://localhost/test" }/** * Created by 1 on 2016/4/9. */ //mongoose.js var mongoose=require('mongoose'); var config=require('./config.js'); module.exports=function(){ var db=mongoose.connect(config.mongodb); require('../model/user.js'); return db; }
2:新建一個model文件夾:在其中新建user.js文件:數據庫
/** * Created by 1 on 2016/4/9. */ var mongoose=require('mongoose'); var userschema=new mongoose.Schema({ username:String, time:Date }); mongoose.model('User',userschema);
3:在app.js中鏈接數據庫:json
var mongoose=require('./config/mongose.js'); var db=mongoose();
4:在路由文件使用操做數據庫;app
var Movie = require('../model/movie'); //找到user的實體類 var mongoose=require('mongoose'); var User=mongoose.model('User'); module.exports = function ( app ) { app.get('/user', function(req, res) { //new 實體類對象; var user=new User({ username:'hahah', time:new Date() }); //對實體類進行保存; user.save(function(err){ if(err){ console.log(err); } //保存成功後,查找全部數據庫對象 User.find({},function(err,docs){ if(err){ console.log(err); } //打印出對象來; res.json(docs); }) }) }); app.get('/index', function(req, res) { Movie.fetch(function(err,movies){ if(err){ console.log('filure'); return; } res.json(movies); }); }); }