Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I’m 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;

2 Answers

0 votes
by (106k points)

You can use below-mentioned code:-

"name": "Jess", 

"location": "Auckland" 

}, 

"name": "Dave", 

"location": "Sydney" 

}, 

"name": "Pete", 

"location": "Brisbane" 

}, 

"name": "Justin", 

"location": "Auckland" 

}, 

]

0 votes
by (50.2k points)

Just imagine your document look 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 only those documents that contain the location as Auckland 

[

    {

        "name": "Jess",

        "location": "Auckland"

    },

    {

        "name": "Justin",

        "location": "Auckland"

    },

]

As you can see, you're looking through the array for a key that matches the field 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 the following:

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);

})

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
2 answers

Browse Categories

...