【发布时间】:2015-01-07 17:04:45
【问题描述】:
我想从 JSON 文件定义我的猫鼬模式。这是我的 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 数据“productJson”定义猫鼬模式。但除非我预先定义我的猫鼬模式,否则它不起作用。有没有办法从我的模型中的 JSON 数据定义猫鼬模式?请问有什么建议吗?
【问题讨论】:
-
除了
slug需要改为item之外,如果您将productJson传递给Schema构造函数,它看起来会起作用。有什么不好的地方? -
如果我将
productJson传递给 Schema 构造函数,则显示“productJson 未定义”的错误。因为 node.js 是一个异步进程。如何在ProductSchema中使用productJson? -
好的,由于缺少缩进,我没有看到
productJson在readFile回调中。因此,也要在回调中移动架构和模型创建。 -
我是
javascript世界的新手。你能解释一下我该怎么做吗?