sails.js beforeCreate方法只接收required设置为true的模型属性

sails.js beforeCreate method receives only the model properties on which required is set to true

本文关键字:设置 true 属性 模型 required beforeCreate js 方法 sails      更新时间:2023-09-26

这是sails.js.中的一个模型

module.exports = {
    attributes: {
        name: {
            type: "string"
        },
        email: {
            type: "email",
            required: true
        },
        password: {
            type: "string"
        }
    },
    beforeCreate: function(values, next) {
        console.log(values); //logs {email:"mail@someplace.com"}
        console.log(values.email);    // logs the email id sent via post
        console.log(values.password);    // logs undefined is required is set to false, If required is set to true, password will log properly.
        next();
    }
};

我计划在beforeCreate函数中对密码进行一些加密,当然我需要密码,现在可以继续使用,但如何管理可选值以备不时之需?

我找到了上述问题的原因,在我的控制器中,我正在创建一个记录,但我正在创建的记录只包含一个字段,即email,见下文:

Users.create({email:req.body.email}).exec(function(err, user){
   // user created
});

模型与插入数据库的对象直接映射,因此内部帆会删除/忽略不存在的字段。若要不删除这些空字段,您可能必须在模型中设置schema:true