Javascript Mongodb find()返回未定义

Javascript Mongodb find()返回未定义,javascript,node.js,mongodb,database,Javascript,Node.js,Mongodb,Database,当我尝试为我的mongodb使用一个简单的find时,它返回undefined var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost:27017/local'; MongoClient.connect(url, function (err, db) { db.collection('pokemon').find({ $search: { $text: 'Pikachu' } }

当我尝试为我的mongodb使用一个简单的find时,它返回undefined

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/local';

MongoClient.connect(url, function (err, db) {

    db.collection('pokemon').find({ $search: { $text: 'Pikachu' } }).toArray(function(err, data){ console.log(data) })

});
编辑:

结果证明我从来没有通过放置

db.collection('pokemon').createIndex({Name: 'text'})

在所有代码之前。

首先,每次您有:

function(err, data){ console.log(data) }
您应该检查错误:

function (err, data) {
  if (err) {
    console.log('Error:', err);
  } else {
    console.log('Data:', data);
  }
}
然后你可能会看到发生了什么

数据库连接本身也是如此,而不是:

MongoClient.connect(url, function (err, db) {
  // use db here
});
您应该处理错误:

MongoClient.connect(url, function (err, db) {
  if (err) {
    // handle errors
  } else {
    // use db here
  }
});

如果您不处理错误,那么您不知道为什么无法获取值,也不要感到惊讶。

首先,每当您遇到以下情况时:

function(err, data){ console.log(data) }
您应该检查错误:

function (err, data) {
  if (err) {
    console.log('Error:', err);
  } else {
    console.log('Data:', data);
  }
}
然后你可能会看到发生了什么

数据库连接本身也是如此,而不是:

MongoClient.connect(url, function (err, db) {
  // use db here
});
您应该处理错误:

MongoClient.connect(url, function (err, db) {
  if (err) {
    // handle errors
  } else {
    // use db here
  }
});

如果您不处理错误,那么您不知道为什么不获取值,也不要感到惊讶。

结果是我忘了创建索引,而我忘了创建索引