MEAN堆栈:不能通过它的id显示来自单个Mongodb元素的数据

时间:2018-05-21 00:09:12

标签: node.js angular mongodb express angular4-httpclient

使用服务和api连接到我能够在catalog.component.ts中显示我的mongodb集合中的整个数组: 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;

服务,我为catalog和getProduct函数添加了getProducts函数以获取详细信息

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

这里我从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);
    });
  }
}

我会看到mongodb的收集 collection 在此列表中: list

我将目录组件中该列表的路由器链接添加到另一个名为' details'的组件中。它有一个&get;来自产品' api中的方法和服务,但视图没有显示元素的名称或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();
  }
}

2 个答案:

答案 0 :(得分:1)

我解决了它,我在api.js中编辑了getProduct方法,在find。()中更改了req.query._id req.body.id,如您所见:

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

我还删除了const id处的'+',并在方法中将另一个变量(product:any)添加到数据中的位置[0]。

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

答案 1 :(得分:0)

MongoDB创建 _id 而不是 id ,您的匹配条件是错误的获取结果。

我已更新查询并添加了控制台日志,如果您现在正在获得预期结果,请检查控制台。

    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)=>{

            console.log("Expected Results: ", result);

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

这可以为您提供单个产品的详细信息。在此处查看您如何使用返回的数据。