Chanatip Yim
Chanatip Yim

Reputation: 366

Sails JS, how to map request parameter to model?

I want to map json data from request.params to model in my controller class. It have some action in controller before save model to database.

Does it has the solution to auto map json data to model object without manually do this?

var email = req.body.email; var phone = req.body.phone;

Upvotes: 1

Views: 336

Answers (1)

user4707474
user4707474

Reputation:

If I understand your question correctly, then yes.

I'll often build forms like this:

<input type="text" name="data[email]" value="[email protected]">
<input type="text" name="data[phone]" value="1234567890">

In your controller:

var data = req.param('data')
// data is now = {email : '[email protected]', phone : '1234567890'}

And when updating database:

User.create(data).exec(funtion(e,r){
    console.log(e||r)
    // if there is no error, object r should contain:
    // {
        id : <id>, 
        email : '[email protected]', 
        phone : '1234567890', 
        createdAt : <date>, 
        updatedAt : <date>
       }
})

Upvotes: 2

Related Questions