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