素材牛VIP会员
连接mongodb时出现错误,Error: collection name must be a String
 随***吧  分类:Node.js  人气:1353  回帖:1  发布于6年前 收藏
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

请教下是为什么?谢谢

 标签:node.js

讨论这个帖子(1)垃圾回帖将一律封号处理……

Lv6 码匠
wt***00 UI设计师 6年前#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官方文档

 文明上网,理性发言!   😉 阿里云幸运券,戳我领取