限制在Sails.js模型中设置的字段

所以我有一个像这样的字段的模型:

// ... slug: { type: 'string', required: true, alphanumeric: true, minLength: 3, maxLength: 16 }, loggedinAt: 'date', // ... 

我正在使用Sails蓝图结构,以便自动映射所有内容。 但是,有时我有像loggedinAt严格内部的字段,我不希望他们能够由用户设置。

如果我使用loggedinAt字段发布post请求,它将会设置它。 我怎样才能限制呢?

您可以使用策略来限制此行为。 在api / policies / restrictUserCreate.js中

 module.exports = function (req, res, next) { // Check for the "loggedInAt" field in the request if (req.param('loggedInAt')) { return res.badRequest("Nuh uh, you can't set that!"); } return next(); } 

或者,只是忽略某些字段(仅限于Sails v0.10.x),请使用黑名单

 module.exports = function (req, res, next) { // Make sure blacklist object exists, and use existing one if possible, // since this policy could be chained req.options.values = req.options.values || {}; req.options.values.blacklist = req.options.values.blacklist || []; // Add restricted fields to the blacklist req.options.values.blacklist.push('loggedinAt'); return next(); } 

然后在config / policies.js中

 // Assuming your controller is "UserController" UserController: { create: "restrictUserCreate" }