【问题标题】:findOne returns undefined on the serverfindOne 在服务器上返回 undefined
【发布时间】:2018-02-26 01:27:01
【问题描述】:

这是我在服务器上的代码:

Meteor.publish('currentRequest', function (requestId) {
        console.log('from publish');
        console.log(requestId) // The id is printed successfully
        console.log(Requests.findOne({_id: requestId})) // returns undefined
        return Requests.findOne({_id: requestId});
    });

项目 ID 已打印,但 .findOne() 似乎不起作用,因为它返回 undefined

我在这里做错了什么?

【问题讨论】:

  • 您的代码看起来不错,但是由于 findOne 没有返回 Mongo 光标,您的发布将无法正常工作。您将需要使用find 函数。
  • @GaëtanRouziès find() 返回空数组。就像没有具有该 _id 但存在的文档一样
  • 您在哪里检查了您的文档是否存在?你从哪里得到这个“id”?手动检查Requests.find().fetch()的内容,我很确定你不会找到你的文档,因为你的查询是正确的并且文档不存在。
  • @GaëtanRouziès Requests.find().fetch() 返回集合中的所有元素。 “_id”看起来像这样,{ _id: { _str: '598d74ebc048c71100e8f730' }

标签: node.js mongodb meteor


【解决方案1】:

.findOne() 以异步方式返回响应。您需要将回调函数传递给 findOne 并在回调函数中使用 return 语句。请看下面的示例代码。

CollectionName.findOne({
     query : query
   }, function(err, resp) {
   if (err) {
     throw err;
   } else {
     return resp;
   }
});

【讨论】:

  • 你错了,在Meteor调用DB是同步的。
【解决方案2】:

您的问题的答案将是:因为没有满足您搜索查询的文档。

根据documentation

查找与选择器匹配的第一个文档,按排序和跳过选项排序。如果没有找到匹配的文档,则返回 undefined

等效于find(selector, options).fetch()[0]options.limit = 1

此外,正如@GaëtanRouziès 所指出的,此发布将不起作用,因为.findOne 返回的是 document/undefined 而不是光标。

【讨论】:

  • "find()" 返回空数组。在数据库中找不到文档
  • @BehrouzRiahi 好吧,您的集合中似乎根本没有文档。不要忘记.find() 返回光标。您应该在此光标上调用.fetch() 以获取找到的文档。
  • Requests.find().fetch() 返回集合中的所有元素。 “_id”看起来像这样,{ _id: { _str: '598d74ebc048c71100e8f730' }
  • @BehrouzRiahi 那么应该很清楚你应该如何在那里找到你的文件。 { '_id._str': requestId }
  • 我试过了,它返回一个对象,但看起来不像预期的那样。下面是它返回的部分内容,我应该编辑问题并将其全部发布吗? “{ _mongo: I20170917-20:21:29.312(4)? { _observeMultiplexers: {}, I20170917-20:21:29.312(4)? _onFailoverHook: { nextCallbackId: 0, 回调: {}, bindEnvironment: true }, I20170917 -20:21:29.312(4)? db: I20170917-20:21:29.312(4)? { 域: null, I20170917-20:21:29.312(4)? _events: {}, "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2017-07-16
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 2017-06-25
  • 1970-01-01
相关资源
最近更新 更多