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

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

#1
  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:
https://learn.freecodecamp.org/apis-and-microservices/mongodb-and-mongoose/use-model-find-to-search-your-database

My project on glitch

{
    "_id": {
        "$oid": "5be82e2d748aa95227510086"
    },
    "favoriteFoods": [
        "pizza"
    ],
    "name": "[email protected]",
    "age": 24,
    "__v": 0
}

#2

try delete in schema unique:true


#3

Just tried but the test didn’t pass.

I get the same error.

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

#4

I think once you created schema, you cant change it. try change mongoose.model(‘Person’,personSchema);
tomongoose.model(‘Person1’,personSchema);


#5

: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?


#6

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.


#7

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.


#8

yes, the red button Delete all documents in collection.