(node.js) node.js怎么连接数据库

最近在学node.js,但是不知道怎么连接数据库。没有文档可以看,求推荐。怎么用node连接mysql mongoDB redis solite?求解答

var mysql = requiremysql;
var connection = mysql.createConnection{ host : localhost, user : me, password : secret, database : my_db
}; connection.connect; connection.querySELECT 1 + 1 AS solution, functionerr, rows, fields { if err throw err; console.logThe solution is: , rows[0].solution;
}; connection.end;

https://github.com/mysqljs/my…

var mongoose = require mongoose // Build the connection string
var dbURI = mongodb://127.0.0.1/my_db
// Create the database connection
mongoose.connectdbURI; mongoose.connection.onconnected, function { console.logMongoose connected to + dbURI;
}
mongoose.connection.onerror,function err { console.logMongoose connection error: + err
}
mongoose.connection.ondisconnected, function { console.logMongoose disconnected
}
process.onSIGINT, function { mongoose.connection.closefunction { console.logMongoose disconnected through app termination process.exit0 }
}

以上是通过mongoose连接mongodb的代码,保存为(db.js,在主程序(假设是app.js中引入

var express = requireexpress;
var db = require./model/db var app = express; //引入一个单独的router
app.use/account, require./routes/account

即可在其他地方(假设是上面引入的一个单独的router account.js)使用mongoose

var express = requireexpress
var mongoose = requiremongoose require../model/user
let UserModel = mongoose.model"User"

数据的model需要单独建立,比如我们建立一个model/user.js文件,以供上面的router引入使用

var mongoose = requiremongoose
var Schema = mongoose.Schema var userSchema = new Schema{ email:{type:String, index:true, unique:true}, unm:{type:String,index:true, unique:true}, password:String, role:{type:String, enum: ["student","controller","gm"], index:true}, lang:[String], regTime:Number, year:String, month:String, day:String,
} mongoose.modelUser,userSchema

—–分割线————————————–

redis可以用于session缓存,(当然也可以用于暂存数据),用做缓存的话类似以下写法,当然我这里为了省事用的是mongodb临时充当缓存数据库

var MongoStore = requireconnect-mongosession app.usesession{ secret: [secret1, secret2], saveUninitialized: false, // dont create session until something stored resave: false, //dont save session if unmodified store: new MongoStore{ url: mongodb://localhost/my_db, touchAfter: 24 * 3600, // time period in seconds ttl: 7 * 24 * 60 * 60 //session过期时间为7天,过期后使用cookies登陆 }
}

mysql连接可以使用库 mysqljs/mysql npm install mysqljs/mysql
mongo连接可以使用库 mongoose npm install mongoose
redis连接可以使用库 redis npm install redis
sqlite连接可以使用库 sqlite3 npm install sqlite3

各个库接口各不相同,请参考官方文档
mysql readme
mongoose guide
redis readme
sqlite3 readme

针对你这种的要不来几个ORM试试??

  • Sequelize

  • Waterline

  • BOOKSHELF.JS

  • node-orm2

  • 。。。。

根据你的需求,你需要连接的数据库类型,是不是需要事务支持之类的,选择合适的吧! 使用orm对你底层数据库类型的切换会友好点。

发表评论

电子邮件地址不会被公开。 必填项已用*标注