When you call mongoose.model()
on a schema, Mongoose compiles a model for you.
The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name. Thus, for the example above, the model Tank is for the tanks collection in the database.
Note: The .model()
function makes a copy of schema
. Make sure that you’ve added everything you want to schema
, including hooks, before calling .model()
!
Constructing Documents
An instance of a model is called a . Creating them and saving to the database is easy.
const Tank = mongoose.model('Tank', yourSchema);
const small = new Tank({ size: 'small' });
small.save(function (err) {
if (err) return handleError(err);
// saved!
// or
Tank.create({ size: 'small' }, function (err, small) {
if (err) return handleError(err);
// saved!
});
Tank.insertMany([{ size: 'small' }], function(err) {
});
Note that no tanks will be created/removed until the connection your model uses is open. Every model has an associated connection. When you use mongoose.model()
, your model will use the default mongoose connection.
mongoose.connect('mongodb://localhost/gettingstarted');
Finding documents is easy with Mongoose, which supports the rich query syntax of MongoDB. Documents can be retrieved using a model
‘s , findById, , or where static methods.
Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);
See the chapter on for more details on how to use the Query api.
Deleting
Models have static deleteOne()
and deleteMany()
functions for removing all documents matching the given filter
.
Tank.deleteOne({ size: 'large' }, function (err) {
if (err) return handleError(err);
// deleted at most one tank document
});
Each model
has its own update
method for modifying documents in the database without returning them to your application. See the docs for more detail.
If you want to update a single document in the db and return it to your application, use findOneAndUpdate instead.
Change Streams
provide a way for you to listen to all inserts and updates going through your MongoDB database. Note that change streams do not work unless you’re connected to a MongoDB replica set.
async function run() {
// Create a new mongoose model
});
const Person = mongoose.model('Person', personSchema);
// Create a change stream. The 'change' event gets emitted when there's a
// change in the database
Person.watch().
on('change', data => console.log(new Date(), data));
// Insert a doc, will trigger the change stream handler above
console.log(new Date(), 'Inserting doc');
await Person.create({ name: 'Axl Rose' });
}
The output from the above will look like what you see below.
2018-05-11T15:05:35.467Z 'Inserting doc'
2018-05-11T15:05:35.487Z 'Inserted doc'
2018-05-11T15:05:35.491Z { _id: { _data: ... },
operationType: 'insert',
fullDocument: { _id: 5af5b13fe526027666c6bf83, name: 'Axl Rose', __v: 0 },
ns: { db: 'test', coll: 'Person' },
documentKey: { _id: 5af5b13fe526027666c6bf83 } }
You can read more about change streams in mongoose in this blog post.
The cover many additional methods available like count, , aggregate, and .
Now that we’ve covered Models
, let’s take a look at Documents.