Mongodb find()返回undefined

时间:2017-02-08 14:24:41

标签: 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' } }).toArray(function(err, data){ console.log(data) })

});

编辑:

原来我从未通过

创建索引
db.collection('pokemon').createIndex({Name: 'text'})

在所有代码之前。

1 个答案:

答案 0 :(得分:4)

首先,每次你拥有:

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
  }
});

如果你不处理错误,那么不要惊讶于你不知道为什么你没有得到价值。