将mongodb函数转换为wait/async
当我调用下面的函数从MongoDB获取数据时,我得到了一个未定义的参数。我怀疑这是因为我需要将函数转换为异步/等待函数。然而,我不知道如何做到这一点,而不打破功能和它们的链条,因为他们的立场?有没有简单的方法将其转换为异步/等待将mongodb函数转换为wait/async,mongodb,typescript,mongoose,Mongodb,Typescript,Mongoose,当我调用下面的函数从MongoDB获取数据时,我得到了一个未定义的参数。我怀疑这是因为我需要将函数转换为异步/等待函数。然而,我不知道如何做到这一点,而不打破功能和它们的链条,因为他们的立场?有没有简单的方法将其转换为异步/等待 studentRoute.route('/read-student/:id').get((req, res) => { Student.findById(req.params.id, (error, data) => { if (
studentRoute.route('/read-student/:id').get((req, res) => {
Student.findById(req.params.id, (error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
在我的角度前端,我有以下服务:
// Get student
GetStudent(id): Observable<any> {
let API_URL = `${this.endpoint}/read-student/${id}`;
return this.http.get(API_URL, { headers: this.headers })
.pipe(
map((res: Response) => {
return res || {}
}),
catchError(this.errorMgmt)
)
}
//获取学生
GetStudent(id):可观察的原来问题与此相同。当数据库返回一个项时,它是一个对象而不是数组。对象的长度未定义
什么是未定义的,客户端的响应data
?@Rashomon res.json(data)返回值。我正在使用的教程。获取所有学生的类似函数仅在res.json(数据)上成功运行。我已经将问题简化为需要将其转换为wait/async。教程中有完整的代码。为什么不将错误消息记录在console.log中,以确定引发错误的真正原因。这是因为mongoose也可以使用您使用的回调方法工作。
import { Component, ViewChild, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router'; // this is needed to get the params from the routes
import { ApiService } from './../../shared/api.service';
import { Student } from './../../shared/student';
import { Web3Service } from './../../shared/web3.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
@Component({
selector: 'app-contract',
templateUrl: './contract.component.html',
styleUrls: ['./contract.component.css']
})
export class ContractComponent implements OnInit {
StudentData: any = [];
dataSource: MatTableDataSource<Student>;
@ViewChild(MatPaginator) paginator: MatPaginator;
displayedColumns: string[] = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l'
];
constructor(
private router: Router,
private actRoute: ActivatedRoute,
private studentApi: ApiService
) {
var id = this.actRoute.snapshot.paramMap.get('id');
this.studentApi.GetStudent(id).subscribe(data => {
this.StudentData = data;
this.dataSource = new MatTableDataSource<Student>(this.StudentData);
setTimeout(() => {
this.dataSource.paginator = this.paginator;
}, 0);
})
}
ngOnInit(): void {
}
}