nodejs连接mongodb的问题

因为初学,跟着书本开始学习使用node-mongodb-native驱动器来操纵mongodb

但是还是因为书本使用的mongodb驱动估计太老旧,采取书本和多数网上的链接方式均报出如下错误

var server = new mongodb.Server('127.0.0.1', 27017, {});

new mongodb.Db('test', server, {}).open(function (err, client) {
    if (err) throw err;
    console.log('\033[96m + \033[39m connected to mongodb');
    app.users = new mongodb.Collection(client, 'maning');
    app.listen(3000, function () {
        console.log('\033[96m + \033[39m app listening on *:3000');
    });
})

报错:大概意思是集合名应该为字符串

D:\Program Files\PM25>node index.js
 +  connected to mongodb
Error: collection name must be a String
    at Error (native)
    at checkCollectionName (D:\Program Files\PM25\node_modules\mongodb\lib\utils
.js:70:11)
    at new Collection (D:\Program Files\PM25\node_modules\mongodb\lib\collection
.js:59:3)
    at D:\Program Files\PM25\index.js:59:19
    at D:\Program Files\PM25\node_modules\mongodb\lib\db.js:227:5
    at connectHandler (D:\Program Files\PM25\node_modules\mongodb\lib\server.js:
280:7)
    at g (events.js:260:16)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at D:\Program Files\PM25\node_modules\mongodb\node_modules\mongodb-core\lib\
topologies\server.js:408:23
D:\Program Files\PM25\node_modules\mongodb\lib\server.js:283
      process.nextTick(function() { throw err; })
                                    ^

Error: collection name must be a String
    at Error (native)
    at checkCollectionName (D:\Program Files\PM25\node_modules\mongodb\lib\utils
.js:70:11)
    at new Collection (D:\Program Files\PM25\node_modules\mongodb\lib\collection
.js:59:3)
    at D:\Program Files\PM25\index.js:59:19
    at D:\Program Files\PM25\node_modules\mongodb\lib\db.js:227:5
    at connectHandler (D:\Program Files\PM25\node_modules\mongodb\lib\server.js:
280:7)
    at g (events.js:260:16)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at D:\Program Files\PM25\node_modules\mongodb\node_modules\mongodb-core\lib\
topologies\server.js:408:23

网上很多博文都有这个错误的发生,但是没有解决的回复,本能是马上去github找原著

还真的发现我又犯傻了,人家在node-mongodb-native2.0的推荐链接方式已经和书上的完全不同

当然我没有看过变更履历,这也是小白的做法,但是长了记性,就是跟着书学编程是不靠谱的。。。凡是找API或者github原著

看过官方的方法后尝试,通过:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  db.close();
});

我自己的连接测试:

var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/test';    

MongoClient.connect(DB_CONN_STR, function(err, db) {
  console.log("连接成功!");
});

 

    原文作者:MongoDB
    原文地址: https://www.cnblogs.com/qianyuqianxun/articles/5100644.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞