【问题标题】:How manipulate res.locals object in request?如何在请求中操作 res.locals 对象?
【发布时间】:2015-10-26 14:02:08
【问题描述】:

我在我的项目中使用node-restful,我想用moment 替换我的日期属性。

当我像下面这样尝试时;

var QuestionResource = app.user = restful.model('Question', questionSchema)
        .methods(['get', 'post', 'put', 'delete']);

    QuestionResource
        .after('get', function(req, res, next) {
            res.locals.bundle.forEach(function(question) {
               res.locals.bundle[res.locals.bundle.indexOf(question)].created_at = moment(question.created_at).fromNow()
            })
            next()
        })

响应数据未更改。为什么?怎么会这样?

提前致谢。

【问题讨论】:

    标签: javascript node.js express momentjs


    【解决方案1】:

    我刚刚通过 github 上的 node-restful 社区帮助解决了我的问题。

    调查一下,似乎是因为返回的模型不是普通对象,而是猫鼬对象的一个​​实例。

    在后期处理中,手动调用toObject()

    res.locals.bundle.forEach(function(question, idx, questions) {
      questions[idx] = question.toObject();
      questions[idx].created_at = moment(question.created_at).fromNow()
    })
    

    【讨论】:

      猜你喜欢
      • 2020-05-31
      • 2014-05-17
      • 2011-08-04
      • 1970-01-01
      • 2017-09-10
      • 2011-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多