express 连接数据库

(1)创建项目 ,项目名cntMongodb

express -e cntMongodb
cd cntMonfodb
npm install
npm install mongoose --save //安装mongoose插件

(2)app.js同级目录下,新建db.js

var mongoose = require("mongoose"); //引入mongoose

var db = mongoose.connection;
db.on('error', function callback() { //监听是否有异常
    console.log("Connection error");
});
db.once('open', function callback() { //监听一次打开
    //在这里创建你的模式和模型
    console.log('connected!');
});

mongoose.connect('mongodb://localhost/helloworld'); //连接到mongoDB的todo数据库
//该地址格式:mongodb://[username:password@]host:port/database[?options]
//默认port为27017
module.exports = mongoose;

(3)在app.js最上方,引入db.js

var db = require('./db');

(4)测试链接 ,在项目目录中,右击,git bash here

node app //启动app

(5)看到以下打印 说明链接成功

 

posted @ 2017-03-16 17:13  Cynthia娆墨旧染  阅读(594)  评论(0编辑  收藏  举报