2016-11-18 39 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 %}