如何在jugglingdb中添加一个自定义属性来build模,并通过JSON返回
如何将一个自定义属性添加到jugglingdb模型? 我想定义一个自定义的属性,特别是与自定义的方法,因为我想把它返回给客户端。
这是一个使用无处不在的Post模型的例子:
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 } });
应用程序/模型/ 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; };
这将通过compound c
在控制台中返回post.time,但不会在post.toJSON()
上post.toJSON()
。
尝试2:
Post.prototype.afterInitialize = function () { Post.defineProperty('time', { type: 'String' }); this.__data.time = moment(this.date).format('hh:mm A'); };
这个尝试是有希望的…它通过.toJSON()
提供了预期的输出。 但是,正如我担心的那样,它也试图用该字段更新数据库。
目前有一个小范围的问题,将阻止价值被打印(它只会显示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 };