MongoDB and Mongoose - Use model.find() to Search Your Database

  1. Use Model.find()

Find all the people having a given name, using Model.find() -> [Person]
In its simplest usage, Model.find() accepts a query document (a JSON
object ) as the first argument, and returns an array of matches.
It supports an extremely wide range of search options. Check it in the docs.
Use the function argument personName as search key.

My code:

var Person = mongoose.model('Person',personSchema);

var findPeopleByName = function(personName, done) {
Person.find({"name":personName},(err,data)=>{
if(err) return done(err)
  return done(null,data)
  })  

};

new code:

var findPeopleByName = function(personName, done) {

var query = Person.find( {name: personName})
    query.exec(function (err, data) {
     if(err) return done(err)
    return done(null,data);     
    }); 
 }

Still not working

If I console log I get ā€œUnauthorizedā€.

image

Itā€™s pretty much the same code Iā€™ve used in the last challenge, I donā€™t understand why but it doesnā€™t work. I also tried looking at the documentation but itā€™s being done in a slightly different way using exec.
https://mongoosejs.com/docs/queries.html

Link to the challenge:

My project on glitch

{
    "_id": {
        "$oid": "5be82e2d748aa95227510086"
    },
    "favoriteFoods": [
        "pizza"
    ],
    "name": "r@nd0mN4m3",
    "age": 24,
    "__v": 0
}
1 Like

try delete in schema unique:true

Just tried but the test didnā€™t pass.

I get the same error.

  name: {
        type:String,
        **unique:true**
},

I think once you created schema, you cant change it. try change mongoose.model(ā€˜Personā€™,personSchema);
tomongoose.model(ā€˜Person1ā€™,personSchema);

:sleepy::sleepy::sleepy:

Iā€™ve used the same exact code but it didnā€™t work anyway. I think Iā€™ve broken somethingā€¦
I wonder if there is something I can do. Should I clear the collections or something?

I copy your code to my and it work.Usualy change the name collections work, but this is waiting for collection named 'Person'
Yes try clear collections in mLAB, the mongoose.deleteModel('Person');*/ not working.

I canā€™t seem to find an option to delete the collections, may I try deleting the document directly?

I just want to make sure I donā€™t do anything I shouldnā€™t.

yes, the red button Delete all documents in collection.

1 Like