From 935492530a6c4809665f640e0d885f2614969201 Mon Sep 17 00:00:00 2001 From: Ai-Lyn Tang Date: Wed, 24 Jul 2019 02:58:42 +1000 Subject: [PATCH] Replace stub for mongoDB lesson (use model.find) (#36491) * Replace stub for mongoDB lesson * Replace stub for "Use model.find to search your database" * Include hints * Include solution * Use callback in `createAndSavePerson()` * fix: corrected hints syntax --- .../index.md | 64 +++++++++++++++++-- 1 file changed, 60 insertions(+), 4 deletions(-) diff --git a/guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database/index.md b/guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database/index.md index 8a48f28965..22cd7aabe7 100644 --- a/guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database/index.md +++ b/guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/use-model.find-to-search-your-database/index.md @@ -1,10 +1,66 @@ --- title: Use model.find() to Search Your Database --- -## Use model.find() to Search Your Database +# Use model.find() to Search Your Database -This is a stub. Help our community expand it. +## Hints -This quick style guide will help ensure your pull request gets accepted. +### Hint #1 +Replace `Model` with the name of your model from the previous sections. Most likely this is `Person`. - +### Hint #2 +Use `{name: personName}` for the first argument in `Model.find()`. + +## Solutions + +
Solution #1 (Click to Show/Hide) + +Code for `myApp.js` + +```javascript +/** 1) Install & Set up mongoose */ +const mongoose = require('mongoose'); +mongoose.connect(process.env.MONGO_URI); + +/** 2) Create a 'Person' Model */ +var personSchema = new mongoose.Schema({ + name: String, + age: Number, + favoriteFoods: [String] +}); + +/** 3) Create and Save a Person */ +var Person = mongoose.model('Person', personSchema); + +var createAndSavePerson = function(done) { + var janeFonda = new Person({name: "Jane Fonda", age: 84, favoriteFoods: ["vodka", "air"]}); + + janeFonda.save(function(err, data) { + if (err) return console.error(err); + done(null, data) + }); +}; + +/** 4) Create many People with `Model.create()` */ +var arrayOfPeople = [ + {name: "Frankie", age: 74, favoriteFoods: ["Del Taco"]}, + {name: "Sol", age: 76, favoriteFoods: ["roast chicken"]}, + {name: "Robert", age: 78, favoriteFoods: ["wine"]} +]; + +var createManyPeople = function(arrayOfPeople, done) { + Person.create(arrayOfPeople, function (err, people) { + if (err) return console.log(err); + done(null, people); + }); +}; + +/** 5) Use `Model.find()` */ +var findPeopleByName = function(personName, done) { + Person.find({name: personName}, function (err, personFound) { + if (err) return console.log(err); + done(null, personFound); + }); +}; +``` +