express中在app.js定义的mongoose.connection为什么能在model层直接使用
之前使用mongoose时候 直接在app.js中这样写
var mongoose = require('mongoose');
//db conn
var dbUrl = 'mongodb://localhost/sand';
mongoose.connect(dbUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'mongodb connection error'));
db.once('open', function(callback) {
console.log('mongodb connection right');
});
然后定义model层
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
var UserSchema = mongoose.Schema({
name: {unique: true, type: String},
password: {type: String},
nickname: {type: String},
role: {type: Number, default: 0}, //0普通用户,1老师, 2管理员
createTime: {type: Date, default: Date.now()}
});
。。。
var User = mongoose.model('User', UserSchema);
module.exports = User;
因为两个mongoose是一样的,app修改了该node空间里面缓存的mongoose,其他require时,从该缓存取出,所以都是一样