Question

How do I add a custom property to a jugglingdb model? I want to define a custom property specifically versus a custom method because I want to return it to the client.

Here is an example using the ubiquitous Post model:

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

app/models/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');
    };
}

I would like to return it like so in 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 });
            });
        });
    });
});

Expected results:

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

Things I've tried in app/models/post.js:

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

This would return post.time in the console via compound c, but not on post.toJSON().

Attempt 2:

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

This attempt was promising...it provided the output expected via .toJSON(). However as I feared, it also tried to update the database with that field as well.

Was it helpful?

Solution

There is currently a small scope issue that will prevent the value from being printed (it will just display time: only), but I've went ahead and made a pull request for that here.

Otherwise, omitting the prototype portion on afterInitialize was successful:

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
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top