Saving an instance

So far we have created an instance, and put some data to it, but it only exists in the application. Saving it to the database is a really simple operation.

Note

Your Mongoose connection must be open for this to work.

After we have created our newUser and given it some data, we save it in the following way:

newUser.save( function( err ){
  if(!err){
    console.log('User saved!');
  }
});

This .save method is an example of an instance method, because it operates directly on the instance, rather than the model. Note that the parameter it takes is a callback function to run when the save operation has been made to the database. As we saw back in Chapter 1, Introducing Mongoose to the Technology Stack, writing to a database is a blocking operation, ...

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.