gpt4 book ai didi

node.js - 平均堆栈 : can't display data from a single Mongodb element by it's id

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:44 25 4
gpt4 key购买 nike

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

我将一个路由器链接添加到目录组件中的该列表,并将所选元素的 id 添加到另一个名为“details”的组件,该组件在 api 和服务中具有“getProduct”方法,但 View 不显示元素的名称或编号:

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

最佳答案

我解决了这个问题,我通过将 find.() 中的 req.query._id 更改为 req.body.id 编辑了 api.js 中的 getProduct 方法,如您所见:

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 处的“+”,并在数据中的位置 [0] 的详细信息方法中添加了另一个变量 (product:any)。

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

关于node.js - 平均堆栈 : can't display data from a single Mongodb element by it's id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50440489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com