Creating and saving database entry in one step
We don't always need to run all the commands separately and can simplify do things by creating and saving the database entry in one step. There are two ways of doing this.
Chaining methods
The first way is to chain the newUser
and .save
commands into one line, for example:
var newUser = new User({ name: 'Simon Holmes', email: 'simon@theholmesoffice.com', lastLogin : Date.now() }).save( function( err ){ if(!err){ console.log('User saved!'); } });
The Model.create() method
The second way is to use a single-model method, which combines the new
and the save
operations into one command. This method takes two parameters. First is the data object, and the second is the callback function that is to be executed after the instance has been saved to the database.
So the blueprint for this method is:
ModelName.create(dataObject,callback)
Let's see this in operation, using our trusty User
model:
User.create({ name: 'Simon Holmes', email: 'simon...