Heim > Fragen und Antworten > Hauptteil
最近在学node.js,但是不知道怎么连接数据库。没有文档可以看,求推荐。怎么用node连接mysql mongoDB redis solite?求解答
学习ing2016-11-09 17:14:20
var mongoose = require( 'mongoose' )// Build the connection stringvar dbURI = 'mongodb://127.0.0.1/my_db'// Create the database connectionmongoose.connect(dbURI); mongoose.connection.on('connected', function () { console.log('Mongoose connected to ' + dbURI); }) mongoose.connection.on('error',function (err) { console.log('Mongoose connection error: ' + err) }) mongoose.connection.on('disconnected', function () { console.log('Mongoose disconnected') }) process.on('SIGINT', function() { mongoose.connection.close(function () { console.log('Mongoose disconnected through app termination') process.exit(0) }) })
以上是通过mongoose连接mongodb的代码,保存为(db.js),在主程序(假设是app.js)中引入
var express = require('express'); var db = require('./model/db') var app = express(); //引入一个单独的router app.use('/account', require('./routes/account'))
即可在其他地方(假设是上面引入的一个单独的router account.js)使用mongoose
var express = require('express') var mongoose = require('mongoose') require('../model/user') let UserModel = mongoose.model("User")
数据的model需要单独建立,比如我们建立一个model/user.js文件,以供上面的router引入使用
var mongoose = require('mongoose')var Schema = mongoose.Schemavar 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.model('User',userSchema)
redis可以用于session缓存,(当然也可以用于暂存数据),用做缓存的话类似以下写法,当然我这里为了省事用的是mongodb临时充当缓存数据库
var MongoStore = require('connect-mongo')(session) app.use(session({ secret: ['secret1', 'secret2'], saveUninitialized: false, // don't create session until something stored resave: false, //don't 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登陆 }) }))
汪汪2016-11-09 17:12:00
var mysql = require('mysql');var connection = mysql.createConnection({ host : 'localhost', user : 'me', password : 'secret', database : 'my_db'}); connection.connect(); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end();