如何使用Node.js和Mongoose处理从MongoDB查询中找到的数据

huangapple go评论84阅读模式
英文:

How to process the data found from a mongodb query using node.js and mongoose

问题

我正在尝试处理从查询中找到的数据。但是,由于某种原因,我无法获取到结果。

我能够看到查询找到了2条记录,但我无法获取实际的记录。
不确定我在哪里搞错了

这是终端中的输出:

{
  message: 'Channels fetched successfully!',
  channels: [],
  maxChannels: 2
}

很奇怪,因为我在我的应用程序的其他地方使用相同的代码片段,它可以完美地返回计数和记录,但这次不行。

所以我只想知道如何处理来自响应的记录。

英文:

I am tryin to process the data found from a query. however, but I am not able to get back the results from it for some reason.

I am able to see it found 2 records from the query, but I cant get the actual records.
not sure where I am messing up here

  const channelQuery =  Channel.find({ fields: { $all: channelFieldsFieldNames } })


  let fetchedChannels;
  channelQuery
    .then(documents => {
      fetchedChannels = documents;
      return Channel.count();
    })
    .then(count => {
      console.log({
        message: "Channels fetched successfully!",
        channels: fetchedChannels,
        maxChannels: count
      });
    })
    .catch(error => {
      console.log(error)
      res.status(500).json({
        message: "Fetching channels failed!"
      });
    });

this is what i see in the terminal:

{
  message: 'Channels fetched successfully!',
  channels: [],
  maxChannels: 2
}

its weird because I use the same snip of code in other places in my app and it returns the count and the records perfectly, but not this time

so i just want to know how to process the records from the response

i found a few similar stackoverflow posts but they didnt did not discuss how they process the data, they only talked about the query itself
https://stackoverflow.com/questions/3305561/how-to-query-mongodb-with-like

答案1

得分: 1

你正在使用两个不同的查询:
return Channel.count(); => 这里你在Mongo中计算所有的频道数
而你的搜索 const channelQuery = Channel.find({ fields: { $all: channelFieldsFieldNames } }) 却找不到任何结果。

英文:

You are using two different querys:
return Channel.count(); => here you count all the Channels in mongo
while your search const channelQuery = Channel.find({ fields: { $all: channelFieldsFieldNames } }) finds nothing

huangapple
  • 本文由 发表于 2023年1月10日 23:53:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75072540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定