2014-05-23 67 views
0

註冊貓鼬模式並使用它們時傳遞配置信息的好方法是什麼?Mongoose Schema註冊 - 傳遞配置信息

說,在下面的例子中,我想使來自一個配置文件讀取偏好和超時值...... "read: ['nearest']}, safe: {wtimeout: 10000})"

像=>"read: [dbConfig.readPrefence]}, safe: {wtimeout: dbConfig.writeTimoutMS})", what's a good way to pass dbConfig?

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var blogSchema = new Schema({ 
    title: String, 
    author: String, 
    body: String, 
    comments: [{ body: String, date: Date }], 
    date: { type: Date, default: Date.now }, 
    hidden: Boolean, 
    meta: { 
    votes: Number, 
    favs: Number 
    } 
}, {read: ['nearest']}, safe: {wtimeout: 10000})); 

回答

0

的解決方案可能取決於您如何組織文件,這意味着您可能會問的是如何將配置傳遞給每個包含模式的多個文件。但首先看一下簡單情況,這個文件中存在一個模式,我建議從那裏加載配置並傳入值。

config.json

{ 
    "read": "nearest", 
    "safe": true 
} 

我-schema.js

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema, 
    config = require('./config.json'); 

var blogSchema = new Schema({ 
    title: String, 
    author: String, 
    body: String, 
    comments: [{ body: String, date: Date }], 
    date: { type: Date, default: Date.now }, 
    hidden: Boolean, 
    meta: { 
     votes: Number, 
     favs: Number 
    } 
}, { 
    read: config.read, 
    safe: config.safe 
}); 

如果你有多個模式,你寧願加載配置只有一次,並通過周圍,那麼我建議在模式文件的require調用中發送它。例如:

app.js

var mySchema = require("./my-schema.js")(config); 

我-schema.js

module.exports = function(config) { ... }