将模式添加到模型

时间:2015-10-20 01:18:03

标签: loopbackjs

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) {

}

我在哪里放置代码?

1 个答案:

答案 0 :(得分: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.

    });
}

现在它将一直有效,直到问题解决。