2015-10-20 66 views
1

https://docs.strongloop.com/display/public/LB/Validating+model+data#Validatingmodeldata-Addingaschematoamodel添加架構模型

從示例代碼不起作用

var productSchema = { 
    "name": { "type": "string", "required": true }, 
    "price": "number" 
}; 

var Product = Model.extend('product', productSchema) 

ReferenceError: Model is not defined 
at Object. (/home/test/dev/common/models/product.js:41:18) 
at Module._compile (module.js:435:26) 
at Object.Module._extensions..js (module.js:442:10) 
at Module.load (module.js:356:32) 
at Function.Module._load (module.js:311:12) 
at Module.require (module.js:366:17) 
at require (module.js:385:17) 
at /home/test/dev/node_modules/loopback-boot/lib/executor.js:219:20 
at Array.forEach (native) 
at defineModels (/home/test/dev/node_modules/loopback-boot/lib/executor.js:200:23) 
Program node . exited with code 1 

project.js

這個樣子的

module.exports = function(Product) { 

} 

我在哪裏放代碼?

回答

0

您可以在project.js中要求環回,並使用它來訪問Model對象。

var loopback = require('loopback'); 
module.exports = function(Product) { 

    var productSchema = { 
     "name": { "type": "string", "required": true }, 
     "price": "number" 
    }; 

    var Product = loopback.Model.extend('product', productSchema); 

    Product.observer('before save', function(context, next) { 
     //check the context.req object for incoming object. 
     //otherwise, search in context object. 
     console.log(context.req); 
     var reqObject = context.req; 

     //get keys of productSchema 
     var allowedFields = Object.keys(productSchema); 

     //Iterate incoming object and delete extra fields 
     //Using delete reqObject.extraField. if not matched to keys in allowedFields. 

    }); 
} 

現在它會爲你工作,直到問題解決。

+0

謝謝。這行得通。但它不會像doc .. 中所述刪除額外的屬性。「如果客戶端嘗試保存具有額外屬性的產品(例如說明),那麼在應用程序將數據保存到模型中之前,將刪除這些屬性。」 – aung

+1

是的,我也發現這個問題。可能與連接器有關?無論如何,你可以在答案中嘗試解決。 –