node.js - Mongoose 从集合中获取所有内容返回一个空列表

标签 node.js angular mongodb typescript mongoose

我在项目中创建了一个新集合,并遵循检索所有用户的相同语法来检索该集合中的所有内容,但由于某种原因我最终得到一个空数组或列表。有人可以告诉我为什么吗,因为我对 MongoDB 相当陌生。下面是我的代码。当我在查询之前放置 console.log 并调用它时,该服务正在被调用。另外,将数据保存到数据库也可以,只是 getAll 我在做时遇到了麻烦。该集合只有一个字段,即帐号。

在我的服务中

async function getAll() {
    return await accountdb.find({});
}

Controller

function getAll(req, res, next) {
    accountdbService.getAll()
        .then(account => res.json(account))
        .catch(err => next(err));
}

在前端我有

 getAll() {
    return this.http.get<account[]>(`${environment.apiUrl}/account`);
  }

最后在组件中

ngOnInit() {
    this.loadAllAccounts();
  }

  private loadAllAccounts() {
    this.AccountService.getAll().pipe(first()).subscribe(account => {
      this.accounts = account;
      console.log(this.accounts);
    });
    console.log(this.accounts);

}

调用api时postman响应:

[
    {
        "_id": "5b89e647e1e6540ac28d68b1",
        "logDataInput": "admin changed the status of user test2 to manager",
        "__v": 0,
        "id": "5b89e647e1e6540ac28d68b1"
    },
    {
        "_id": "5b89e648e1e6540ac28d68b2",
        "logDataInput": "admin changed the status of user test2 to User",
        "__v": 0,
        "id": "5b89e648e1e6540ac28d68b2"
    },
    {
        "_id": "5b8a2a6b16206e0cae8c71ba",
        "logDataInput": "admin deactivated user test2",
        "__v": 0,
        "id": "5b8a2a6b16206e0cae8c71ba"
    }
]

network tool 2 api calls picture

最佳答案

看起来您在 getAll 函数的响应中发送了错误的变量。

    .then(logTrack => res.json(account)

将其更改为

    .then(logTrack => res.json(logTrack)

关于node.js - Mongoose 从集合中获取所有内容返回一个空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52125425/

相关文章:

javascript - 在 node.js 中捕获需要模块的错误

Angular2 - FormGroup 在 RC6 中包含和排除替换项

接口(interface)的 Typescript 风格指南

mongodb - MongoDB中Grails中命名查询的列表方法中的排序不区分大小写

node.js - 如何对 Google Cloud Pub/Sub 队列进行速率限制

node.js - 如何从express-stormpath库中自定义注销的redirectURL?

javascript - MongoDB $cmp(聚合)给出错误结果

angular - 我想从我的 Angular 2 应用程序中的服务执行重定向

node.js - 如何克隆 Mongoose 模式?

python - 如何远程登录 mongodb(通过 pymongo)并获取 db.serverStatus() 的输出