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

查看:613
本文介绍了node.js - 连接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

请教下是为什么?谢谢

解决方案

根据文档,不能使用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官方文档

这篇关于node.js - 连接mongodb时出现错误,Error: collection name must be a String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆