Search code examples
reactjsdatabasemongodbmongodb-querymean-stack

How to get all the data from Mongo db collection in my MEAN stack app?


I am creating a MEAN stack app I have mongo DB (atlas) connected to it (working properly) but now I want to get all the data that I stored in my database. How can I do that? Below is my code snippet-

this is my .ts file

constructor(private route: ActivatedRoute, private router: Router, private ds: DataService) { }




getAllLocations(){
    this.ds.getLocations().subscribe((d) => {
      this.locationObject = d;
      console.log(this.locationObject);
  })
}

this is my data service file

 getLocations():any{
  return this.http.get('http://localhost:3000/get-locations');
 }

 

this is my index.js file(react file)

app.post('/get-locations', bodyParser.json(), (req, res) => {

var collection = connection.db(dbName).collection('user_2');

collection.find({}).toArray((err, docs) => {
    if (!err) {
        res.send({ status: "ok", data: docs })
    }
    else {
        res.send({ status: "failed", data: err });
    }
})

})

all this code is giving me 2 errors

    GET http://localhost:3000/get-locations 404 (Not Found)
ERROR HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:3000/get-locations", ok: false, …}

Also, my database is not empty and has this type of structure like-

 { latitude : value, longitude : value}
    { latitude : value, longitude : value}
    { latitude : value, longitude : value} 

Solution

  • here is the solution

    this.ds.getLocations()
      .subscribe((response)=>{
        if(response.status=="ok")
        {
          alert('locations fetched successfully');
          // console.log(response.data);
          this.userlist = response.data;
          this.checkingNearby();
        }
        else{
          alert("locations cant be fetched ");
         //  alert(JSON.stringify(response.data));
        }
      })
    
    
    
    
    
     getLocations():any{
      return this.http.post('http://localhost:3000/get-locations',"");
     }
    

    and its working.