MONGOOSE FUNDAMENTALS
Review
In this lesson, you learned how to use Mongoose to interact with a MongoDB database. Let’s review some of the topics that we covered:
Mongoose is a Node package that interacts with a running MongoDB database.
MongoDB stores documents in collections and collections of documents in databases. Each document has key-value pairs as entries.
Using a Schema, we can set the structure of documents dynamically, using paths with schema types and validators.
Models are JavaScript classes that we compile from our Schema definitions.
You can use models to create, read, update, and delete documents from a database.
You can query a database using .find() and .findOne(). Mongo also provides query operators to allow for more complex queries.
Mongoose also allows for the creation of methods associated with a database:
.statics() adds static “class” methods to the Models itself.
.methods() adds an instance method to documents.
const {mongoose, runWithDatabase} = require('./database');
const manyItems = require('./items');
const magicItemSchema = new mongoose.Schema({
item: {
type: String,
required: true
},
magicalProperty: {
type: String ,
required: true
},
unitCost: {
type: Number,
required: true
},
totalUnits: {
type: Number,
required: true
}
})
magicItemSchema.statics.findMostExpensive = function(callback) {
return this.findOne({}).sort('unitCost').exec(callback);
}
magicItemSchema.methods.use = function(callback) {
this.totalUnits = this.totalUnits - this.unitCost;
return this.save();
}
const MagicItem = mongoose.model('MagicItem', magicItemSchema);
runWithDatabase(async () => {
await MagicItem.create(manyItems);
const mostExpensive = await MagicItem.findMostExpensive();
console.log(`The most expensive object is the ${mostExpensive.item}`);
console.log(`The ${mostExpensive.item} started with ${mostExpensive.totalUnits} charges.`);
console.log(`Using ${mostExpensive.item}...`)
await mostExpensive.use();
console.log(`The ${mostExpensive.item} has ${mostExpensive.totalUnits} charges left.`);
});
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const env = process.env.NODE_ENV || 'development';
const databaseUrl = process.env.DATABASE_URL || `mongodb://localhost/learn-mongoose_${env}`;
const options= {
useMongoClient: true,
};
const runWithDatabase = async (runWhileConnected) => {
console.log('connecting to database...\n');
await mongoose.connect(databaseUrl, options);
console.log('dropping old data...\n');
await mongoose.connection.db.dropDatabase();
console.log('running function...\n');
await runWhileConnected();
console.log('\n');
console.log('disconnecting from database...\n');
await mongoose.disconnect();
console.log('complete!\n');
};
module.exports = {
mongoose,
runWithDatabase,
};
module.exports = [
{
item: "cloak" ,
magicalProperty: "invisibility",
unitCost: 25,
totalUnits: 300,
},
{
item: "ring" ,
magicalProperty: "invulnerability" ,
unitCost: 30,
totalUnits: 250,
},
{
item: "boots" ,
magicalProperty: "shrink" ,
unitCost: 40,
totalUnits: 200,
}
]