gpt4 book ai didi

node.js - 如何向 jugglingdb 中的模型添加自定义属性并通过 JSON 返回它

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:52 24 4
gpt4 key购买 nike

如何将自定义属性添加到 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 }
});

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

我想像 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() 上返回。

尝试2:

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

这次尝试很有希望...它通过 .toJSON() 提供了预期的输出。然而,正如我担心的那样,它也尝试使用该字段更新数据库。

最佳答案

目前存在一个小范围问题,会阻止打印该值(它只会显示 time: ),但我已经继续为该 here 发出拉取请求。

否则,在 afterInitialize 上省略原型(prototype)部分会成功:

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

关于node.js - 如何向 jugglingdb 中的模型添加自定义属性并通过 JSON 返回它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18220230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com