3

I am trying to fetch data from MongoDB-atlas using note.js which I have manually fed to the server.

The status of the collection on MongoDB-atlas sever is :

dbname: viit collection name : viit_atts

also, I have whitelisted my id and I am able to connect to the server.

I started off by connecting to the server by using the command :

mongoose.connect("mongodb+srv://wimpy_cool:myPassWordGoesHere@cluster0-phqid.mongodb.net/test?retryWrites=true&w=majority",{},function(err,res)
{
        if(err)
        {
            console.log("mongo lab server not connected");
            console.log(err);
        }
        else
        {
            // console.log(res);
            console.log("Connectd to mongolab db");
        }
});

Now using mongoose I have declared schema and made a model and then use the find function to fetch the data.

var bodyParser = require('body-parser');
var mongoose =require("mongoose");
var express= require("express");
var app = express();

app.use(bodyParser.urlencoded({extended:true}));

    mongoose.connect("mongodb+srv://wimpy_cool:myPassWordGoesHere@cluster0-phqid.mongodb.net/test?retryWrites=true&w=majority",{},function(err,res)
    {
            if(err)
            {
                console.log("mongo lab server not connected");
                console.log(err);
            }
            else
            {
                // console.log(res);
                console.log("Connectd to mongolab db");
            }
    });


var viit_att_schema = new mongoose.Schema({
    name : String,
    no_of_present: Number,
    no_of_absent: Number
});

var att_history_schema = new mongoose.Schema({
    time : String ,
    att_stats : String,
});



var viit_att= mongoose.model("viit_att",viit_att_schema);

var att_history = mongoose.model("att_history",att_history_schema);

var list_of_all_members;
var list_of_all_members_sorted;

viit_att.find({},function(err,viit_atts)
{
    if (err) {
        console.log("OH NO ERROR");
    }
    else
    {
        console.log("fetching data now");
        console.log(viit_atts);
        list_of_all_members=viit_atts;
        // console.log(list_of_all_members[0]);
        // console.log(list_of_all_members);
        list_of_all_members_sorted = list_of_all_members.sort(function(a,b) {
                    return b.no_of_present - a.no_of_present ;
                });

        console.log(list_of_all_members_sorted);
    }
});

app.listen( process.env.PORT || 3000 , function(){
    console.log("SERVER 3000 HAS STARTED");
});

But the fetching doesn't seem to take place, the console says this :

D:\MY PROJECTS\WEB\club_attendence_website>node backend.js
(node:13076) DeprecationWarning: current URL string parser is deprecated, 
and will be removed in a future version. To us
e the new parser, pass option { useNewUrlParser: true } to 
MongoClient.connect.
SERVER 3000 HAS STARTED
Connectd to mongolab db
fetching data now
[]
[]
ImInYourCode
  • 567
  • 1
  • 7
  • 19
Kshitij dhyani
  • 591
  • 1
  • 6
  • 14

5 Answers5

4

The problem was that the default connection string for MongoDB atlas has a default database name as test, and will search for the same in the cluster, hence even though it will connect, nothing will be fetched.

In order to learn how to explicitly mention the dbName refer to this link: Fail to connect Mongoose to Atlas

Kshitij dhyani
  • 591
  • 1
  • 6
  • 14
2

Hi I had the same issue!

Issue: I created a mongoDb Atlas collection name is "main"; however when I connect my nodeJs using mongoose, the collection name from the callback became "mains".

Solution: I changed my model name to "mains" and it worked.

Try this: ‍var viit_att= mongoose.model("viit_atts",viit_att_schema);‍

iminiki
  • 2,549
  • 12
  • 35
  • 45
1

Try doing it like this:

viit_att.find({}).then(content => {

        console.log("data was fetched");
        console.log(content);
        list_of_all_members=content;
        // console.log(list_of_all_members[0]);
        // console.log(list_of_all_members);
        list_of_all_members_sorted = list_of_all_members.sort(function(a,b) {
                 return b.no_of_present - a.no_of_present ;
             });

        console.log(list_of_all_members_sorted);
})
.catch(err => { console.log("OH NO AN ERROR") })

ImInYourCode
  • 567
  • 1
  • 7
  • 19
1

I got into this same problem, what worked for me, was to specify a collection name when defining your mongoose models:

module.exports = mongoose.model('App', schema,  COLLECTION_NAME)

Where COLLECTION_NAME must match the mongodb atlas collection name.

Theophilus Omoregbee
  • 2,463
  • 1
  • 22
  • 33
0


For me the problem was that I was unable to fetch or get data but the connection was established with the server and I found that the few problems that can occur are:-

1: URL encoding

The text you put inside the connection string must be url encoded as said in the mongodb docs.
So, if the parameters you put inside the connection string like your database name or your password, the special characters that are : / ? # [ ] @ must be url encoded (also known as percentage encoded), e.g. @ becomes %40. You can use a bunch of online url encoders which are available on the internet.

2: Not added IP address from mongodb UI

You have to add the IP address of the computer from which the database will be sent a request. You can either do it in the first step while connecting by clicking 'Connect' on the cluster page or add ip address from here.
I personally kept it to be accessible by everyone, so added the ip address 0.0.0.0/0 (includes your current IP address).

3: Not specifying the correct database name

If you paste the default connection string in your app, it will point to the default database that is test. You will have to either change test to your db name or if there's nothing written, you'll have to write your db name
So, your connection string should look like this:-
mongodb+srv://<Your username>:<Your password>@cluster0.ezmvoas.mongodb.net/<Your db name>?retryWrites=true&w=majority

Troubleshoot

If there is any other problem, what you can do is to give error as an input to the callback function and try logging the error on the console.

const connectToMongo = () => {
    mongoose.connect(mongoURI, (error, result) => {
        console.log('Connected to MongoDB' + '\nError: ' + error);
    });
}

By this way, you can get the fix for exactly the error message without trying different things.

Hope this solves the problem, Thanks!

Ayush
  • 565
  • 1
  • 7
  • 20