我试图弄清楚如何通过JSON文件定义Mongoose模式的键。到目前为止,我现在尝试实现的代码如下:
const schemaData = require('./myData.json')
const mySchema = new mongoose.Schema();
schemaData.pages.forEach(page => {
page.forEach(subpages => {
mySchema.add(subpage.uniqueID : {type: String, default: ''});
}
};
我已经看到了一些有关如何通过JSON定义模式的示例,但是现在似乎还没有任何动态定义键名的方法?
答案 0 :(得分:1)
您可以遍历Json的键,然后使用[key]: { type: 'String', default: '' }
添加一个对象。该代码段使用一个简单的对象(而不是模式)运行一个示例。
let schema = {};
let jsonData = {
foo: 'foo45',
bar: 'bar',
toto: 'toto'
}
Object.keys(jsonData).map(function(key) {
schema[key] = { type: 'String', default: ''}
});
console.log(schema);
const mySchema = new mongoose.Schema({});
const schemaData = require('./myData.json')
// map down to where you need to get your subpages
Object.keys(subpages).map(function(key) {
mySchema.add({
[key]: { type: 'String', default: ''}
});
});
console.log(mySchema.paths);
这将给出:
{ _id:
ObjectId {
path: '_id',
instance: 'ObjectID',
validators: [],
getters: [],
setters: [ [Function: resetId] ],
options: { auto: true, type: [Function] },
_index: null,
defaultValue: { [Function: defaultId] '$runBeforeSetters': true },
[Symbol(mongoose#schemaType)]: true },
foo:
SchemaString {
enumValues: [],
regExp: null,
path: 'foo',
instance: 'String',
validators: [],
getters: [],
setters: [],
options: { type: 'String', default: '' },
_index: null,
defaultValue: '',
[Symbol(mongoose#schemaType)]: true },
bar:
SchemaString {
enumValues: [],
regExp: null,
path: 'bar',
instance: 'String',
validators: [],
getters: [],
setters: [],
options: { type: 'String', default: '' },
_index: null,
defaultValue: '',
[Symbol(mongoose#schemaType)]: true },
toto:
SchemaString {
enumValues: [],
regExp: null,
path: 'toto',
instance: 'String',
validators: [],
getters: [],
setters: [],
options: { type: 'String', default: '' },
_index: null,
defaultValue: '',
[Symbol(mongoose#schemaType)]: true } }