我想从 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 数据“productJson”定义 Mongoose 模式。但除非我预先定义我的 Mongoose 模式,否则它不起作用。有没有办法从我的模型中的 JSON 数据定义 Mongoose 模式?请问有什么建议吗?
最佳答案
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);
关于json - 从 JSON 文件定义 Mongoose 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26859976/