MEAN 堆栈:无法通过其 id 显示来自单个 Mongodb 元素的数据

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

使用服务和 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;

我为目录添加了 getProducts 函数并为详细信息添加了 getProduct 函数的服务

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 集合中获取数组 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

我将路由器 link 添加到目录组件中的列表,并将所选元素的 ID 添加到另一个名为 'details' 的组件,该组件在 api 中有一个 'getProduct' 方法,并且服务,但视图不显示元素的名称或 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();
  }
}

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

这应该会为您提供单个产品的详细信息。在此处检查您如何使用返回的数据。

我解决了,我在 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);
    });
  }