连接mongodb时出现错误,Error: collection name must be a String

var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017);
new mongodb.Db('test01', server).open(function(err, client) {
  if (err) throw err;
  console.log('connected to server');
  var collection = new mongodb.Collection(client,'student');
  collection.find(function(err, cursor) {
    cursor.each(function(err, doc) {
      if (doc) {
        console.log(doc.uname);
      }
    });
  });
});

这是一段书上的例子,执行代码的时候出现了下面这种情况:

Error: collection name must be a String
图片描述

请教下是为什么?谢谢

阅读 6k
1 个回答

根据文档,不能使用Collection直接构造Collection实例:

Collection()
Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)

正确代码如下:

var Db = require('mongodb').Db,
    Server = require('mongodb').Server

var db = new Db('test01', new Server('localhost', 27017));

db.open(function(err, client) {
  if (err) throw err;
  console.log('connected to server');
  var collection = db.collection('student');
  collection.find(function(err, cursor) {
    cursor.each(function(err, doc) {
      if (doc) {
        console.log(doc.uname);
      }
    });
  });
});

参考MongoDB官方文档

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题