我正在从我的架构中构建字段名称及其类型的对象:
var ret = {};
ThisCollection.schema.eachPath(function(path) {
ret[path] = ThisCollection.schema.path(path).instance;
});
除非模式中有嵌套数组,否则这很好。我似乎无法弄清楚如何访问子文档及其字段'类型。我试过了:
ThisCollection.schema.path("dot.notation").instance
在递归函数中构建更深路径的点符号名称。这似乎不起作用。
示例模式:
var Person = new Schema({
person_code: String,
person_name: String,
location_details:[{
location_name: String,
location_code: String
}]
});
要清楚,我正在寻找我的返回对象以匹配我的结构中的模式,因此嵌套模式是我的返回对象中的嵌套对象,如:
{
person_code: String,
person_name: String,
location_details:{
location_name: String,
location_code: String
}
}
答案 0 :(得分:3)
最简单的解决方案可能是简单地保存您用来创建架构的架构定义对象:
var personSchemaDef = {
person_code: String,
person_name: String,
location_details: [{
location_name: String,
location_code: String
}]
};
var personSchema = new Schema(personSchemaDef);
var Person = mongoose.model('person', personSchema, 'people');
但您也可以从架构的tree
属性中获取架构的层次结构细节:
console.log(Person.schema.tree)
输出:
{ person_code: [Function: String],
person_name: [Function: String],
location_details:
[ { location_code: [Function: String],
location_name: [Function: String] } ],
_id:
{ type: { [Function: ObjectId] schemaName: 'ObjectId' },
auto: true },
id:
VirtualType {
path: 'id',
getters: [ [Function: idGetter] ],
setters: [],
options: {} },
__v: [Function: Number] }
答案 1 :(得分:1)
这里的关键是从路径创建一个对象,特别是带有点符号字符串的路径。您可以使用以下方法设置给定属性和值的对象;
var ret = {};
var setObject = function(name, schema, context) {
var parts = name.split("."),
p = parts.pop(),
value = schema.path(p).instance;
for(var i=0, j; context && (j=parts[i]); i++){
context = (j in context ? context[j] : context[j]={});
}
return context && p ? (context[p]=value) : undefined; // Object
}
ThisCollection.schema.eachPath(function(path) {
setObject(path, ThisCollection.schema, ret);
});
答案 2 :(得分:0)
你可以通过
获得一个subdoc的属性类型[Collection].schema.paths.[sub-doc].schema.paths.[sub-doc-property].instance // it will give dataytpe
您可以将其嵌套为您拥有的嵌套子博客数量
您的收藏品可以使用
ThisCollection.schema.paths.location_details.schema.paths.location_name.instance // String
_
/**
* @param {Object} coll - Collection
* @param {string} props - properties, eg. "abc", "abc.xyz", upto n number of nested dot notation
*/
function getType(coll, props) {
return props.split('.').reduce(function (p, n, index, array) {
if (index < array.length - 1) {
return p.schema.paths[n];
}
return p.schema.paths[n].instance;
}, coll);
}
var type = getType(ThisCollection, "location_details.location_name");
console.log(type); // String