首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在jugglingdb中添加自定义属性并通过JSON返回

如何在jugglingdb中添加自定义属性并通过JSON返回
EN

Stack Overflow用户
提问于 2013-08-13 22:22:57
回答 1查看 625关注 0票数 2

如何将自定义属性添加到杂耍模型?我想具体地定义一个自定义属性,而不是自定义方法,因为我想将它返回给客户端。

下面是一个使用普适的Post模型的示例:

db/schema.js:

代码语言:javascript
复制
var Post = schema.define('Post', {
    title:     { type: String, length: 255 },
    content:   { type: Schema.Text },
    date:      { type: Date,    default: function () { return new Date;} },
    timestamp: { type: Number,  default: Date.now },
    published: { type: Boolean, default: false, index: true }
});

app/model/post.js:

代码语言:javascript
复制
var moment = require('moment');

module.exports = function (compound, Post) {
    // I'd like to populate the property in here.
    Post.prototype.time = '';

    Post.prototype.afterInitialize = function () {
        // Something like this:
        this.time = moment(this.date).format('hh:mm A');
    };
}

我想在app/控制器/posts_Controller.js中这样返回它:

代码语言:javascript
复制
action(function index() {
    Post.all(function (err, posts) {
        // Error handling omitted for succinctness.
        respondTo(function (format) {
            format.json(function () {
                send({ code: 200, data: posts });
            });
        });
    });
});

预期成果:

代码语言:javascript
复制
{
  code: 200,
  data: [
    { 
      title: '10 things you should not do in jugglingdb',
      content: 'Number 1: Try to create a custom property...',
      date: '2013-08-13T07:55:45.000Z',
      time: '07:55 AM',
      [...] // Omitted data
  }, 
  [...] // Omitted additional records
}

我在app/model/post.js中尝试过的东西:

尝试1:

代码语言:javascript
复制
Post.prototype.afterInitialize = function () {
    Object.defineProperty(this, 'time', {
        __proto__: null,
        writable: false,
        enumerable: true,
        configurable: true,
        value: moment(this.date).format('hh:mm A')
    });

    this.__data.time    = this.time;
    this.__dataWas.time = this.time;
    this._time          = this.time;
};

这将通过compound c返回控制台中的compound c,而不是在post.toJSON()上返回。

企图2:

代码语言:javascript
复制
Post.prototype.afterInitialize = function () {
    Post.defineProperty('time', { type: 'String' });
    this.__data.time  = moment(this.date).format('hh:mm A');
};

这一尝试是promising...it通过.toJSON()提供了预期的输出。然而,正如我所担心的,它也试图用该字段更新数据库。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-09 18:40:53

目前有一个小范围的问题,它将阻止打印值(它只显示time: ),但是我已经开始为那个这里发出了一个拉请求。

否则,忽略afterInitialize上的原型部分是成功的:

代码语言:javascript
复制
Post.afterInitialize = function () {
    this.time = moment(this.date).format('hh:mm A'); // Works with toJSON()
    this.__data.time = this.time;                    // Displays the value using console c
};
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18220230

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档