For this two part homework assignment, you will be using some mongoose commands and you will be reading documentation to find new queries/techniques to complete the following activities. Researching queries and implementing them is a big part of this homework!
Utilize the following resources to research the commands you will need:
- Your notes from today
- MongoDB Manual
- Mongoose Docs
- Shahzad's cheatsheet
-
Start your mongo server with
mongod
-
Open a new terminal tab and navigate to your homework folder for tonight which includes:
- A folder for your
vampire_app
- A file for writing your app called
app.js
. You will write your code in here (even for the database). Comment out your database commands as you get them working so that you're only running one at a time. This is where we will be looking for your work after you turn it in. - A file called
populateVampires.js
that includes data on vampires that you will add (later).
npm init
. Install and requiremongoose
.
A schema is a way to organize, ahead of time, what a group of data is going to look like. This can be at various levels of a database depending on what kind of databases you are using.
Mongo, is schema-less on the database level. It doesn't care what the data looks like and will take in virtually anything as long as it's syntactically correct.
Even when you are using MongoDB, an inherently schema-less database, a schema can be very helpful. It helps control what is going into the database so that you can both know what is going into it, and to make validations. Note that with MongoDB, even if a piece of data is not a part of your original schema, you can still store it.
This is where mongoose comes in. Instead of manually making sure everything we are putting into our database makes sense and conforms to some type of structure, Mongoose allows us to define schemas.
Mongoose, in the background, can enforce these schemas (as strictly as you like) in order to make sense of the data going into the database and to allow validation. It provides powerful and simple to use tools to do this.
Lets design a schema using mongoose and then use it to create some documents and eventually query for those documents.
-
Create a folder inside your
vampire_app
calledmodels
. -
Create a file inside your
models
folder calledvampire.js
(singular). You will create your schema and model in this file.
To start your schema:
const vampireSchema = new Schema({
//write your schema fields here
});
A typical object in our vampire collection will look something like this:
const vampire = {
name: 'Count Chocula',
hair_color: 'brown',
eye_color: 'brown',
dob: new Date(1971, 2, 13, 7, 47),
loves: ['cereal','marshmallows'],
location: 'Minneapolis, Minnesota, US',
gender: 'm',
victims: 2,
}
- Build a vampire schema and model that matches the object above. Export your model.
Pause. Take a minute to do a little research and come up with an answer to this question: What's the difference between a Schema and a Model?
-
Go to the Mongoose documentation to learn more about validations and defaults: http://mongoosejs.com/docs/api.html
-
The name field is required, so make sure that the schema accommodates for that.
-
Also, no vampire will have less than 0 victims, so add that into the schema as a validation.
-
Lastly, set the default value of the hair color to blonde.
-
Set up your
vampire_app.js
file to connect to yourvampires
database. -
You may now test your schema with the automated tests by running
npm test
in your terminal.
π΄ The commit message should read:
"Commit 1 - made a schema"
Insert into the database using create method:
- Using the js objects of vampires in
populateVampires.js
, add the vampires to a vampires collection.
You can do this simply by providing this array to the insert method and it will create a document for each object in the array.
- You have a choice to either paste the entire array into this insert command OR you could just export the array into a variable and insert it with the variable name.
Vampire.collection.insertMany(vampireData,(err, data) => {
console.log("added provided vampire data")
mongoose.connection.close();
});
- Using the create method, create 4 new vampires with any qualities that you like two should be male and two should be female.
π΄ The commit message should read:
"Commit 2 - added data into vampire collection"
Write a different query for each of the following:
- Find all the vampires that that are females
- have greater than 500 victims
- have fewer than or equal to 150 victims
- have a victim count is not equal to 210234
- have greater than 150 AND fewer than 500 victims
π΄ The commit message should read:
"Commit 3 - queried for vampires"
Select all the vampires that:
- have a title property
- do not have a victims property
- have a title AND no victims
- have victims AND the victims they have are greater than 1000
π΄ The commit message should read:
"Commit 4 - selected vampires"
Select all the vampires that:
- are from New York, New York, US or New Orleans, Louisiana, US
- love brooding or being tragic
- have more than 1000 victims or love marshmallows
- have red hair or green eyes
π΄ The commit message should read:
"Commit 5 - selected more vampires"
Before you continue on to part two: check it out/remember: Mongoose has some sweet helper functions that can make all this a little easier. See below
Mongoose's default find gives you an array of objects. But what if you know you only want one object? These convenience methods just give you one object without the usual array surrounding it.
Article.findById('5757191bce5579b805705900', (err, article)=>{
console.log(article);
});
Article.findOne({ author : 'Matt' }, (err, article)=>{
console.log(article);
});
Article.findByIdAndUpdate(
'5757191bce5579b805705900', // id of what to update
{ $set: { author: 'Matthew' } }, // how to update it
{ new : true }, // tells findOneAndUpdate to return modified article, not the original
(err, article)=>{
console.log(article);
});
});
Article.findOneAndUpdate(
{ author: 'Matt' }, // search criteria of what to update
{ $set: { author: 'Matthew' } }, // how to update it
{ new : true }, // tells findOneAndUpdate to return modified article, not the original
(err, article)=>{
console.log(article);
});
});
Article.findByIdAndRemove('5757191bce5579b805705900', (err, article)=>{
console.log(article); // log article that was removed
});
Article.findOneAndRemove({ author : 'Matt' }, (err, article)=>{
console.log(article); // log article that was removed
});
Select all the vampires that:
- love either frilly shirtsleeves or frilly collars
- love brooding
- love at least one of the following: appearing innocent, trickery, lurking in rotting mansions, R&B music
- love fancy cloaks but not if they also love either top hats or virgin blood * Hint-You will also have to use $nin *
π΄ The commit message should read:
"Commit 6 - selected even more vampires"
Select all vampires that:
- love ribbons but do not have brown eyes
- are not from Rome
- do not love any of the following: [fancy cloaks, frilly shirtsleeves, appearing innocent, being tragic, brooding]
- have not killed more than 200 people
π΄ The commit message should read:
"Commit 7 - used negative selections on vampire data"
- replace the vampire called 'Claudia' with a vampire called 'Eve'. 'Eve' will have a key called 'portrayed_by' with the value 'Tilda Swinton'
- replace the first male vampire with another whose name is 'Guy Man', and who has a key 'is_actually' with the value 'were-lizard'
π΄ The commit message should read:
"Commit 8 - replaced vampire data"
- Update 'Guy Man' to have a gender of 'f'
- Update 'Eve' to have a gender of 'm'
- Update 'Guy Man' to have an array called 'hates' that includes 'clothes' and 'jobs'
- Update 'Guy Man's' hates array also to include 'alarm clocks' and 'jackalopes'
- Rename 'Eve's' name field to 'moniker'
- We now no longer want to categorize female gender as "f", but rather as fems. Update all females so that the they are of gender "fems".
π΄ The commit message should read:
"Commit 9 - updated vampire data"
- Remove a single document wherein the hair_color is 'brown'
- We found out that the vampires with the blue eyes were just fakes! Let's remove all the vampires who have blue eyes from our database.
π΄ The commit message should read:
"Commit 10 - remove vampire data"
-
Make an index route that will
res.send()
(or even better--res.json()
--look it up!) the json of all the data in our database. -
If number 1 was easy, try to connect your database to your application and show a proper index page that displays your vampire data. If this is also easy, create a show page as well where you are showing individual vampire data.
-
Have extra time? Try out a few more problems on CodeWars
π΄ The commit message should read:
"Commit 11 - tackled some Hungry for More"