2

カスタム プロパティをjugglingdbモデルに追加するにはどうすればよいですか? クライアントに返す必要があるため、カスタム メソッドに対してカスタム プロパティを明確に定義したいと考えています。

以下は、ユビキタスな Post モデルを使用した例です。

デシベル/schema.js:

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 }
});

アプリ/モデル/post.js:

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/controllers/posts_controller.js で次のように返したいと思います:

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

予想された結果:

{
  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/models/post.js で試したこと:

試行 1:

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;
};

これはコンソールで post.time を 経由compound cで返しますが、 では返しませんpost.toJSON()

試行 2:

Post.prototype.afterInitialize = function () {
    Post.defineProperty('time', { type: 'String' });
    this.__data.time  = moment(this.date).format('hh:mm A');
};

この試みは有望でした... 経由で期待される出力が提供されました.toJSON()。しかし、私が恐れていたように、そのフィールドでもデータベースを更新しようとしました。

4

1 に答える 1

1

現在、値が出力されないという小さなスコープの問題があります (表示time:のみになります) 。

それ以外の場合、プロトタイプ部分の省略afterInitializeは成功しました:

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
};
于 2013-09-09T18:40:53.617 に答える