If you remember from Chapter 1, Introducing Mongoose to the Technology Stack, a model is a compiled version of the schema.
A single instance of a model maps directly to a single document in the database. With this 1:1 relationship, it is the model that handles all document interaction—creating, reading, saving, and deleting.
This makes the model a very powerful tool.
Building the model, as we have seen, is pretty straightforward. When using the default Mongoose connection we can call the mongoose.model
command, passing it two arguments:
So if we were to build a model from our user schema we would use this line:
mongoose.model( 'User', userSchema );
If using a named Mongoose connection, the approach is very similar. Using the adminConnection
example from Chapter 2, Establishing a Database Connection:
adminConnection
.model( 'User', userSchema );
We'll be looking at how we interact with the data in the next chapter, but it is useful to have a good understanding of how a model works.
After building the User
model, using the previous line we could create two instances.
var userOne = new User({ name: 'Simon' }); var userTwo = new User({ name: 'Sally' });
Each instance is a JavaScript object that we can interact with.
console.log(userOne.name); // 'Simon' userOne.name = 'Simon Holmes'; console.log(userOne.name); // 'Simon Holmes'
As each new User
is an instance of the model, we are able to use the power of the model to save it to the database as shown in the following code:
userTwo.save(function (err) { if (err) return handleError(err); // userTwo (Sally) is saved! }); userOne.save(function (err) { if (err) return handleError(err); // userOne (Simon Holmes) is saved! });
If we ask Mongoose to "find one", we expect a single instance to be returned. This looks like the following code snippet:
User.findOne({'name' : 'Sally', function(err,user) { if(!err){ console.log(user); } });
The output of this console.log
is a single instance:
{ name: 'Sally', _id: 515c6b47596acf8e35000001, __v: 0 }
If we use a "find many" command, we expect to get an array of instances:
User.find({}, function(err, users) { if(!err){ console.log(users); } });
The output of this console.log
is an array of instances:
[ { name: 'Sally', _id: 515c6b47596acf8e35000001, __v: 0 }, { name: 'Simon Holmes', _id: 515c6b47596acf8e35000002, __v: 0 } ]
Unless specified, the MongoDB collection will be a pluralized (lowercase) version of the model name. See the following for example:
mongoose.model( 'User', userSchema );
The previous line will reference a collection called users
. If the collection doesn't exist it will create it the first time a document is saved using the model.
18.221.129.19