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官方文档