Once you have defined the Schema
object for a model, you need to compile it into a Model
object. When Mongoose compiles the model, it uses the connection to the MongoDB database established by mongoose.connect()
to ensure that the collection is created and has the appropriate indexes, as well as required and unique settings, when applying changes.
The compiled Model
object acts in much the same way as the Collection
object defined in Chapter 13. It provides the functionality to access, update, and remove objects in the model and subsequently in the MongoDB collection.
To compile the model, you use the model()
method in the mongoose
module. The model()
method has the following syntax:
model(name, [schema], [collection], [skipInit])
The name
parameter is a string you can use to find the model later, using model(name)
. The schema
parameter is the Schema
object discussed in the previous section. The collection
parameter is the name of the collection to connect to if one was not specified in the Schema
object. The skipInit
option is a Boolean that defaults to false
. When it is true
, the initialization process is skipped, and a simple Model
object with no connection to the database is created.
The following is an example of compiling the model for the Schema
object defined in Listing 16.2:
var Words = mongoose.model('Words', wordSchema);
You can then access the compiled Model
object at any time by using the following:
mongoose.model('Words')