2016-11-18 40 views
2

为什么使用nunjucks在mongoose对象中循环显示元数据?为什么要通过Mongoose对象显示元数据?

我在使用我正在写的应用程序中使用mongodb和nunjucks。

我试图遍历一个名为persona的模型,但这样做会显示与记录关联的猫鼬元数据。

如果我只是通过编写{{persona}}显示persona变量。

我的输出如下。只是在我的模式中定义的键/值。

{ _id: 582f186df1f05603132090d5, name: 'Alex', name_lower: 'alex', __v: 0, 
meta: { validated: null, contributors: 'Research Team', sources: '4 Interviews' }, 
pain_points: { points: 'Debugging' }, 
ideal_day: { responsibilities: 'Coding websites.', goals: 'Finish the research site.', joys: 'Good code, Good food.', hobbies: 'Dance, Hiking, Eating' }, 
environment: { workspace: 'Desk', tools: 'Atom, Sketch', info_from: null, info_to: null, coworkers_relationship: null, technology_relationship: null }, 
basic_info: { jobtitle: 'FED', experience: '2', education: 'CS', company: '' } } 

然而,如果通过persona

 

    {% for name, item in persona %} 
     {{ name }} : {{ item }} 
    {% endfor %} 

除了显示在我的架构的按键我环路,与记录相关联的所有元数据,猫鼬,也将显示。我想了解为什么当我循环播放对象时显示不同的信息。

 

    $__ 
    isNew 
    errors 
    _doc 
    $__original_save 
    save 
    _pres 
    _posts 
    $__original_validate 
    validate 
    $__original_remove 
    remove 
    db 
    discriminators 
    __v 
    id 
    _id 
    meta 
    pain_points 
    ideal_day 
    environment 
    basic_info 
    updated_at 
    created_at 
    name_lower 
    name 
    schema 
    collection 
    $__handleSave 
    $__save 
    $__delta 
    $__version 
    increment 
    $__where 

我能够用猫鼬的lean()来解决这个问题,但还是不明白,为什么我经历了这种行为。

回答

2

当您拨打{{persona}}时,则结果为persona.toString()
如果对象没有覆盖方法toString那么结果将是[Object object](默认toString方法)。

当您使用循环{% for key, value in persona %}那么它等于

for(var key in obj) 
    print(key + ' - ' + obj[key]); 

此代码打印的所有对象的属性和方法。

要排除方法,您必须使用下一个循环

for(var key in obj) 
    if (typeof(obj) != 'function') // or obj.hasOwnProperty(key) 
     print(key + ' ' + obj[key]); 

所以,为了避免您的问题,你必须“清除”数据之前将它传递给nunjucks或输出之前。
您可以定义custom filter

var env = nunjucks.configure(... 

env.addFilter('lean', function(obj) { 
    var res = {}; 
    for(var key in obj) 
     if (typeof(obj) != 'function') // or obj.hasOwnProperty(key) 
      res[key] = obj[key]; 
    return res; 
}); 
... 
{% for key, value in persona | lean %} 
{{key}} - {{value}} 
{% endfor %}