Sails.js JSON的自定义视图
我们如何在Sails模型上定制JSON?
我创build了一个库存模型
``` module.exports = { attributes: { id: {type: 'integer'}, quantity: {type: 'integer'}, name: {type: 'string'}, description: {type: 'string'} } ```
然而,我得到的默认模型有像createdAt,updateAt这样的附加属性
Inventory.find({}).sort('id asc').exec(function(err, i){console.log}
我想在json上有自定义属性,就像添加一些属性,我知道我们可以通过在控制器上写代码来定制。
但是我们可以在json上自定义视图吗? 像ruby jbuilder。现在写res.view()
只支持HTML。
首先,您可以使用res.json()
而不是res.view()
或rest.ok()
将自动协商JSON和HTML。
Sails.js允许您自定义特定模型的JSON,或者您可以自定义您的一揽子响应types,或者您可以将所需的任何自定义属性附加到要在控制器中发回的JSON对象。
在模型中使用.toJson()
重写http://sailsjs.org/documentation/reference/waterline-orm/records/to-json https://github.com/balderdashy/waterline-docs/blob/master/models /instance-class-methods.md#toobjecttojson
或创build自定义响应types,如res.myJson()
http://sailsjs.org/documentation/concepts/custom-responses
或者,最后,在你的控制器中,你可以创build任何你想要的对象,只需将它传回res.toJson()