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.
The first way is to chain the newUser
and .save
commands into one line, for example:
var newUser = new User({ name: 'Simon Holmes', email: '[email protected]', lastLogin : Date.now() }).save( function( err ){ if(!err){ console.log('User saved!'), } });
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: '[email protected]', lastLogin : Date.now() }, function( err, user ){ if(!err){ console.log('User saved!'), console.log('Saved user name: ' + user.name); console.log('_id of saved user: ' + user._id); } });
This is arguably the neater way of doing a brand new create and save operation, and is the approach we'll be using in our MongoosePM application later. The cost of the compact nature of this approach is that it is less flexible, as we can't do anything with the newUser
instance between creating it and saving it. If you need this flexibility, then go for the new
and save
approach, like in the following:
var newUser = new User({name: 'Simon Holmes'}) newUser.email = '[email protected]'; var rightNow = Date.now(); newUser.createdOn = rightNow; newUser.lastLogin = rightNow; // some more operations on newUser newUser.save( function( err, user ){ if(!err){ console.log('_id of saved user: ' + user._id); } });
3.129.19.251