7

Im having trouble using the .find() function within mongoose on a node js server I've been trying to use this but I cannot get the key information out of my database.

user.find({key: 1} , function(err, data){
  if(err){
    console.log(err);
  };
  console.log("should be the key VVV");
  console.log(data.key);
});

I'm mainly just having trouble wrapping my head around how this function takes queries and gives you back the response from your DB. If someone can break it down id be very thankful the mongoose docs weren't much help.

Also this is my user schema if it helps

var userSchema = new mongoose.Schema({
  username: {type: String, unique: true},
  password: {type: String},
  key: {type: String},
  keySecret: {type: String}
}, {collection: 'user'});


var User = mongoose.model('user',userSchema);

module.exports = User;

3 Answers 3

14

If you imagine your DB looking like this:

[
    {
        "name": "Jess",
        "location": "Auckland"
    },
    {
        "name": "Dave",
        "location": "Sydney"
    },
    {
        "name": "Pete",
        "location": "Brisbane"
    },
    {
        "name": "Justin",
        "location": "Auckland"
    },
]

executing the following query;

myDB.find({location: 'Brisbane'})

will return:

[
    {
        "name": "Pete",
        "location": "Brisbane"
    }
]

While myDB.find({location: 'Auckland'}) will give you

[
    {
        "name": "Jess",
        "location": "Auckland"
    },
    {
        "name": "Justin",
        "location": "Auckland"
    },
]

As you can see, you're looking through the array for a key that matches the one you're looking to find and gives you back all of the documents that match that key search in the form of an array.

The Mongoose interface gives this data to you in the form of a callback, and you just need to look for the item inside of the array it returns

user.find({location: "Auckland"}, function(err, data){
    if(err){
        console.log(err);
        return
    }

    if(data.length == 0) {
        console.log("No record found")
        return
    }

    console.log(data[0].name);
})
4
  • I think you gave the best answer. I was going to jump in but; you created a lot of value here. Good answer. Commented Jan 15, 2018 at 7:27
  • Thank you, an alternative to .find() is .findOne() - .find() returns and array, while .findOne() returns the first record it finds(object), ignoring the rest. This is good in cases where you are looking up documents with a unique field - like by email, or ID.
    – David Alsh
    Commented Jan 16, 2018 at 1:01
  • 1
    @darshanan do you mean how do you search through values in nested keys on a document? If so it's db.collections.find({"keyOne.keyTwo":"search"})
    – David Alsh
    Commented May 24, 2018 at 23:56
  • @DavidAlsh Please look into above comment. Commented May 25, 2018 at 6:49
4

Maybe you should use

Model.findOne({key: '1'}, function(err, data) {
  console.log(data.key);
});

find() will get a doc array, and findOne() can get just one doc.

Your field key is String type, so your query obj shoule be {key: '1'}, not {key: 1}.

Read the mongoose docs carefully may help you.

1
  • I tried doing this just to test the only problem i have with doing it this way is i'm confused how to point the db to the right entry when just using find one key. There are multiple instances of user accounts and keys.
    – Echo
    Commented Jan 16, 2018 at 8:03
0

hi my friend I use this method to retrieve data from db I hope that can help

user.find({key: 1})
   .then((userOne)=>{
       //if is an API
       res.status(200).json({data : userOne});
       //OR
       // if you had a view named profile.ejs for example
       res.render('/profile',{data : userOne, title : 'User profile' }); 
            console.log(userOne); // just for check in console
        })
    .catch((error)=>{
        //if an api
        res.status(400).json({messageError : error});
        // OR if not an api
        res.render('/profile',{data : 'No data of this profile',errorToDisplay : error})
    });
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.