使用Mongodb:TypeError:无法读取undefined的属性'collection'

时间:2016-11-26 07:44:44

标签: node.js mongodb

在执行https://www.freecodecamp.com/challenges/store-data-in-mongodb

时遇到此问题

错误消息

swyx:~/workspace $ learnyoumongo run find.js
/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/mongodb/lib/server.js:231
        process.nextTick(function() { throw err; })
                                      ^

TypeError: Cannot read property 'collection' of undefined
    at Exercise.<anonymous> (/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/exercises/find/exercise.js:37:5)
    at next (/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:271:17)
    at Exercise.end (/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:277:5)
    at Workshopper.end (/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:191:12)
    at Workshopper.done (/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/workshopper/workshopper.js:323:19)
    at Exercise.<anonymous> (/home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:160:14)
    at /home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/workshopper-exercise/exercise.js:147:16
    at /home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/exercises/find/exercise.js:20:21
    at /home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/mongodb/lib/mongo_client.js:238:20
    at /home/ubuntu/.nvm/versions/node/v4.6.1/lib/node_modules/learnyoumongo/node_modules/mongodb/lib/db.js:242:14

这里还有其他类似的问题,但没有一个描述这个确切的问题

作为参考,这是我在

上运行它的(有效)代码
var mongo = require('mongodb').MongoClient
var age = process.argv[2]

var url = 'mongodb://localhost:27017/learnyoumongo'

mongo.connect(url, function(err, db) {
  if (err) throw err
  var parrots = db.collection('parrots')
  parrots.find({
    age: {
      $gt: +age
    }
  }).toArray(function(err, docs) {
    if (err) throw err
    console.log(docs)
    db.close()
  })
})

2 个答案:

答案 0 :(得分:1)

解决方案是我的mongodb服务器在一夜之间遇到意外关机,甚至没有运行。要重新启动它,你必须恢复(https://docs.mongodb.com/manual/tutorial/recover-data-following-unexpected-shutdown/),然后重新启动。

答案 1 :(得分:0)

在MongoDB本机NodeJS驱动程序的2.x版本中,您将获取数据库对象作为连接回调的参数:

mongo.connect(url, (err, db) => {
  // Database returned
});

但是根据3.0的changelog,你现在得到一个包含数据库对象的客户端对象:

mongo.connect(url, (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});

close()方法也已移至客户端,因此您必须编写client.close();而不是db.close()