【问题标题】:Access mongoose non-schema values in Jade在 Jade 中访问 mongoose 非模式值
【发布时间】:2013-05-15 10:57:14
【问题描述】:

我在 Jade 中有一个非常奇怪的问题,我无法访问架构中未定义的值。

我在我的架构上使用strict:false 并将值保存到其中。我的数据如下所示:

{
 "title" : "This is a title in the schema",
 "notInSchema" : "This will never show up"
}

这行得通:

h1= post.title 

这不起作用:

h1= post.notInSchema

如果我将所有数据转储到模板中,我可以看到两条数据:

pre= JSON.stringify(options,null,'\t')      //{"title" : "This is a title in the schema", "notInSchema" : "This will never show up"}

如果我将notInSchema 添加到我的架构中,它就会显示出来。我怎么能做到这一点而不添加它?

【问题讨论】:

    标签: node.js mongodb express mongoose pug


    【解决方案1】:

    不要将原始 Mongoose 文档传递给 Jade,而是传递其序列化版本:

    res.render('yourtemplate', {
      post : post.toJSON() // .toJSON() is also called by JSON.stringify()
    });
    

    我相信 Mongoose 只会在文档上为架构中的字段创建访问器。任何其他字段,即使它们存储在数据库中,也没有得到,因此无法直接访问。

    documentation 似乎暗示了类似的东西:

    注意:在您的实例中不存在的任何键/值集 无论架构选项如何,架构总是被忽略。

    编辑:因为您正在处理结果集,所以您需要在其中的每个文档上调用 toJSON。最简单的方法是使用map(希望我的 CF 语法正确):

    res.render "admin",
      title   : "Admin Dashboard"
      results : results
      users   : results.users.map (user) ->
        user.toJSON()
      messages: req.flash() || {}
    

    尽管这仍然会使results '未处理'。或者,您可以将映射保留到 async.series 中的单独步骤。例如:

     Company
       .find()
       .exec (err,companies)->
         next(null,companies.map (company) ->
           company.toJSON()
         )
    

    或者在您的模板中使用toJSON,用于您需要访问这些“非架构”属性的任何对象。

    【讨论】:

    • 如何将 Mongoose 结果传递给您的模板?
    • 这里是整个函数,我想在所有东西上都使用它,但options是现在最重要的gist.github.com/wesbos/bd274e9f7112e4476522
    • @Wes 编辑了我的答案,希望对您有所帮助。
    • @Wes map/toJSON 操作的快捷方式是:users : JSON.parse(JSON.stringify(result.users))(看起来有点傻,但工作原理几乎相同)
    【解决方案2】:

    我用:

    model.find({Branch:branch},function (err, docs){
    if (err) res.send(err)
    
     res.render('index', 
        {tree: tree,
          articulos: JSON.parse(JSON.stringify(docs)) 
        })})
       });
    

    【讨论】:

      猜你喜欢
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2011-11-09
      • 2017-05-08
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多