Skip to content
This repository has been archived by the owner on Jan 4, 2019. It is now read-only.

Create new instance function #1

Closed
arjan123 opened this issue Sep 23, 2014 · 9 comments
Closed

Create new instance function #1

arjan123 opened this issue Sep 23, 2014 · 9 comments

Comments

@arjan123
Copy link

Request:

It would be great if there was a function that create an instance of a model including including all the properties with default values, calculated fields aso.

(maybe such a function is already there?)

ps. I'm studying on the code at the moment...

@martijndeh
Copy link
Owner

You can create a new model instance by invoking the below. This also inserts the model in the datastore.

models.User.create({
    name: 'Arjan'
});

If you want to retrieve any existing model instances, you can use e.g.:

models.User.findOne({
    name: 'Arjan'
});

Is this what you mean?

@arjan123
Copy link
Author

Almost,

I mean more like this

models.User.new().then(function(user)
{
});
to create a new User instance including default/initial values etc...
where user gives me f.e.

{
name: '',
username: '',
password: '',
isCompany: true, //initial value,
receiveNewsLetter: true,

etc....
}

@martijndeh
Copy link
Owner

I see. Without actually inserting the user in the datastore, I assume?

@arjan123
Copy link
Author

Yes that's correct. It's just convenience....

@martijndeh
Copy link
Owner

Model#new should be fairly easy to implement. When accessing properties, some would be undefined though, as they are set through SQL statements (only after creating or selecting). I also feel it might introduce issues and confusion, as Model#new implies it's creating a new model instance and inserts it in the datastore, but it's actually just creating the instance.

A similar idea is something like:

var user = new models.User();
user.name = 'Arjan';
user.save();

What do you think of that?

@avandijk
Copy link

Yes I agree that's more elegant.

@martijndeh
Copy link
Owner

How's the reading going and did you see the latest features?

@arjan123
Copy link
Author

I like those new features. Especially sockets. I've to figure out the new sources yet.
You develop more quickly than I can read!!

I've also setup a test project to try some of the features.
I'll keep you informed about my test results....

thx

@martijndeh
Copy link
Owner

In 0.41.0 we introduced a ModelInstance#new method. This creates a new model instance without persisting it to the datastore. When calling ModelInstance#save on the object it'll persist to the datastore.

The below creates a Pie instance and saves it to the datastore:

var pie = PieModel.new();
pie.type = 'Apple';
pie.save()

ModelInstance#new is isomorphic so it's available on both the front- and the back-end.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants