Search code examples
node.jsangularmongodbexpressangular4-httpclient

MEAN stack: can't display data from a single Mongodb element by it's id


using a service and api to connect to I was able to display the whole array from my mongodb collection in catalog.component.ts : api.js

const express = require('express');
const router=express.Router();

const app=express();
const MongoClient=require('mongodb').MongoClient;
const ObjectID=require('mongodb').ObjectID;
var path=require('path');
var db;

const connection=(closure) => {
    return MongoClient.connect('mongodb://localhost:27017', (err, client)=>{
        if (err) return console.log(err);
        db=client.db('angulardb');
        closure(db);

    });
};


const sendError =(err, res)=>{
    response.status=501;
    response.message=typeof err == 'object' ? err.message : err;
    res.status(501).json(response);
};

let response={
    status:200,
    data:[],
    message: null
};

router.post('/getProducts',(req, res) => {

  connection((db) => {
    db.collection('products')
      .find()
      .toArray()
      .catch((err)=>{
        sendError(err, res);
        response.message ={ success:"Se obtuvieron los registros correctamente", error:""};
        res.send({response});
      })
      .then((result)=>{

        response.data= result;
        res.send({response});
      });
  });
});

router.post('/getProduct',(req, res) => {
  connection((db) => {
    db.collection('products')
      .find({id:new ObjectID(req.query.id)})
      .toArray()
      .catch((err)=>{
        sendError(err, res);
        response.message ={ success:"Se obtuvieron los registros correctamente", error:""};
        res.send({response});
      })
      .then((result)=>{

        response.data= result;
        res.send({response});
      });
  });
});
module.exports=router;

service where I added the getProducts function for catalog and getProduct function for details

mongo2.service.ts:

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/toPromise';
import {HttpClient, HttpHeaders} from '@angular/common/http';
@Injectable()
export class Mongo2Service {

  constructor( private _http: HttpClient) { }


  getProducts() {
    const headers = new HttpHeaders({'Content-Type': 'application/json' });
    return this._http.post('/api/getProducts', { headers })
      .catch( (error: any) => Observable.throw(error || 'server error'));
  }

  getProduct(id: number) {
    const headers = new HttpHeaders({'Content-Type': 'application/json' });
    const params = {'id': id};
    return this._http.post('/api/getProduct', { headers, params})
      .catch( (error: any) => Observable.throw(error || 'server error'));
  }
}

Here I get the array from mongodb collection catalog.component.ts:

import { Component, OnInit } from '@angular/core';
import {Mongo2Service} from '../mongo2.service';

@Component({
  selector: 'app-catalog',
  templateUrl: './catalog.component.html',
  styleUrls: ['./catalog.component.css']
})
export class CatalogComponent implements OnInit {
products: any;
respuesta: any;


  constructor( private mongo2Service: Mongo2Service) {}

  ngOnInit() {
  this.getProducts();

  }

  getProducts() {

    this.mongo2Service.getProducts().subscribe(respuesta => {
      this.respuesta = respuesta;
      this.products = this.respuesta.response.data;
      console.log(this.respuesta);
    });
  }
}

And I get displayed the mongodb collecction collection in this list: list

I add a router link to that list in catalog component with the selected element's id to another component called 'details' which has a 'getProduct' method in api and the service, but the view doesn't display the element's name or id:

import { Component, OnInit } from '@angular/core';
import {Location} from '@angular/common';
import {ActivatedRoute} from '@angular/router';
import {Mongo2Service} from '../mongo2.service';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {

  respuesta: any;
  products:any;

    constructor(private location: Location,
    private route: ActivatedRoute,
   ,private mongo2Service: Mongo2Service) { }

  ngOnInit() {
  this.getProduct();
  }


  getProduct() {
    const id=+ this.route.snapshot.paramMap.get('_id');
    console.log('entro funcion componente');

    this.mongo2Service.getProduct(id).subscribe(respuesta => {
      this.respuesta = respuesta;
      this.products = this.respuesta.response.data; 
      console.log(this.respuesta);
    });
  }

  goBack(): void{
  this.location.back();
  }
}

Solution

  • I solved it , I edited the getProduct method in api.js by changing req.query._id for req.body.id inside find.() as you can see:

    router.post('/getProduct',(req, res) => {
      var find={ id: new ObjectID(req.body.id) };
      console.log(find);
      connection((db) => {
        db.collection('products')
          .find({_id:new ObjectID(req.body.id)})
          .toArray()
          .catch((err)=>{
            sendError(err, res);
            response.message ={ success:"Se obtuvieron los registros correctamente", error:""};
            res.send({response});
          })
          .then((result)=>{
            response.data= result;
            res.send({response});
          });
      });
    });
    

    I also deleted the '+' at the const id and added another variable (product:any) to the method in details with the position [0] in data.

     getProduct() {
    
        const id = this.route.snapshot.paramMap.get('_id');
    
        console.log(id);
        this.mongo2Service.getProduct(id).subscribe(respuesta => {
          this.respuesta = respuesta;
          this.product = this.respuesta.response.data[0];
          console.log(this.respuesta);
        });
      }