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 ...

Get Mongoose for Application Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.