从JSON文件定义Mongoose模式

时间:2014-11-11 07:47:12

标签: json node.js mongoose

我想从JSON文件定义我的mongoose模式。这是我的JSON文件结构:

   {    
        "default": [
            {
                "item": "productTitle",
                "label": "Product Title",
                "note": "e.g Samsung GALAXY Note 4",
                "type": "text",
                "required": "Product Name cannot be blank..."
            },
            {
                "item": "productCode",
                "label": "Product Code",
                "type": "text",
                "required": "Product Code cannot be blank..."
            }    
        ]}

这是我的node.js模型:

// Load the module dependencies
var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var fs = require('fs');
var file = __dirname + '/product.server.model.json';

// Read the json file
fs.readFile(file, 'utf8', function (err, data) {

data = JSON.parse(data);

var productJson = {};
for(var  i = 0; i < data.default.length; i++) {

    productJson[data.default[i].slug] = {
        type: 'String',
        required: data.default[i].required,
        default: '',
        trim: true
    }

}

});

// Define a new 'ProductSchema'
var ProductSchema = new Schema(
   // Here I want to put JSON Data 'productJson'
);

// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);    

我尝试了一切可能的方法来定义JSON数据和产品Json&#39;中的mongoose模式。但除非我预先定义我的mongoose架构,否则它无效。有没有办法在我的模型中从JSON数据定义mongoose模式?有什么建议吗?

1 个答案:

答案 0 :(得分:0)

fs.readFile是一个异步函数,这意味着它会立即返回,然后通过您提供的回调函数将其结果提供给调用者作为第三个参数。

因此,您需要暂停使用productJson,直到其填充在该回调中。这意味着也要在回调中移动模式和模型创建。

fs.readFile(file, 'utf8', function (err, data) {

    data = JSON.parse(data);

    var productJson = {};
    for(var  i = 0; i < data.default.length; i++) {

        // Changed .slug to .item here as I don't see slug in the JSON
        productJson[data.default[i].item] = {
            type: 'String',
            required: data.default[i].required,
            default: '',
            trim: true
        }
    }

    // Define a new 'ProductSchema'
    var ProductSchema = new Schema(productJson);

    // Create the 'Product' model out of the 'ProductSchema'
    mongoose.model('Product', ProductSchema);
});

此处可以使用的另一种方法是使用同步fs.readFileSync方法来读取文件。这在这样的启动/初始化情况下很有用,在这种情况下,在处理此文件之前,应用程序作为一个整体不应继续。

var data = fs.readFileSync(file, 'utf8');
data = JSON.parse(data);

var productJson = {};
for(var  i = 0; i < data.default.length; i++) {

    // Changed .slug to .item here as I don't see slug in the JSON
    productJson[data.default[i].item] = {
        type: 'String',
        required: data.default[i].required,
        default: '',
        trim: true
    }
}

// Define a new 'ProductSchema'
var ProductSchema = new Schema(productJson);

// Create the 'Product' model out of the 'ProductSchema'
mongoose.model('Product', ProductSchema);
相关问题