mongoose中的connect和createConnection

官网: https://mongoosejs.com

connect

只连接一个数据库时可使用这种方式(连接的是默认连接)

connect(uri(s), [options], [callback])
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:pass@localhost:port/database');
mongoose.connection.on('error', () => {
  console.log('Mongoose connection error')
});
mongoose.connection.on('open', () => {
  console.log('Mongoose connection success')
});
//
var Schema = new mongoose.Schema({
});
var Model = mongoose.model('xxxx', Schema);

createConnection

需要连接多个数据库时必须使用这种方式(是一个连接实例)

createConnection([uri], [options])
var mongoose = require('mongoose');
var db  = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
db.on('error', () => {
  console.log('Mongoose connection error')
});
db.on('connected', () => {
  console.log('Mongoose connection success')
});
//
var Schema = new mongoose.Schema({
});
var Model = db.model('xxxx', Schema);// 这里必须使用db不能是mongoose

你可能感兴趣的:(mongoose中的connect和createConnection)