Mongoose Schema注册 - 传递配置信息

时间:2014-05-23 19:09:49

标签: javascript node.js mongodb mongoose

在注册mongoose架构并使用它们时传递配置信息的好方法是什么?

在下面的例子中说,我想让读取首选项和超时值来自配置文件...... "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}));

1 个答案:

答案 0 :(得分: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) { ... }