Search icon
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Mongoose for Application Development

You're reading from  Mongoose for Application Development

Product type Book
Published in Aug 2013
Publisher Packt
ISBN-13 9781782168195
Pages 142 pages
Edition 1st Edition
Languages
Author (1):
Simon Holmes Simon Holmes
Profile icon Simon Holmes

Table of Contents (18) Chapters

Mongoose for Application Development
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Introducing Mongoose to the Technology Stack 2. Establishing a Database Connection 3. Schemas and Models 4. Interacting with Data – an Introduction 5. Interacting with Data – Creation 6. Interacting with Data – Reading, Querying, and Finding 7. Interacting with Data – Updating 8. Interacting with Data – Deleting 9. Validating Data 10. Complex Schemas 11. Plugins – Re-using Code Index

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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}