错误:集合名称必须是节点js中的字符串

时间:2015-09-03 12:21:22

标签: javascript node.js mongodb

我正在尝试在服务器上运行以下代码

var express = require("express"),
    app = express(),
    bodyParser = require('body-parser'),
    errorHandler = require('errorhandler'),
    methodOverride = require('method-override'),
    hostname = process.env.HOSTNAME || 'localhost',
    port = parseInt(process.env.PORT, 10) || 4004,
    publicDir = process.argv[2] || __dirname + '/public';
var exec = require('child_process').exec;
var fs = require('fs');
 var mongodb = require('mongodb'),
    serverdb = new mongodb.Server('127.0.0.1', 27017, {}),
    dbName = new mongodb.Db('prisync', serverdb, {});
var url = "urlinfo";


//Show homepage
app.get("/", function (req, res) {
  //res.redirect("/index.html");
  console.log("shubham ");
  dbName.open(function (error, client){
      var collection = new mongodb.Collection(client , url);   //line 24 ====
      collection.find().limit(20).toArray(function (err, dataObjArr){
        var data = '';
        var dataArr = [];
        var i = dataObjArr.length;
        //check for error
        if(err){return res.end('error!'+err);}
        //Data
        if(dataObjArr){
          while(i--){
            dataArr[i] = dataObjArr[i]._id;
          }
          data = dataArr.join(' ');
          res.render('/index.html',{ returnedData : data });
        }else{
          res.end();
        }

      });


      });
  });



app.get("/search", function (req, res){
  console.log("shubham batra");
   var pro_name = req.query.name;
   var pro_code = req.query.code;
   var pro_category = req.query.category;
   var pro_brand = req.query.brand;

 pro_name = pro_name+"";
 pro_code = pro_code+"";
 pro_brand = pro_brand+"";
 pro_category = pro_category+"";



  MongoClient.connect('mongodb://127.0.0.1:27017/prisync', function(err, db) {
  if (err) throw err;
    console.log("Connected to Database");


    var documen = {name:pro_name, code:pro_code , category:pro_category, brand:pro_brand };
     //documen = JSON.stringify(documen);
  //insert record
  db.collection('urlinfo').insert(documen, function(err, records) {
    if (err) throw err;

    });

  res.redirect("/index.html");

});
});
//Search page
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static(publicDir));
app.use(errorHandler({
  dumpExceptions: true,
  showStack: true
}));

console.log("Server showing %s listening at http://%s:%s", publicDir, hostname, port);
app.listen(port);

但在尝试加载 localhost:4004

时出现以下错误
Server showing /home/shubham/Music/pricesync/server/public listening at http://localhost:4004
shubham 

/home/shubham/node_modules/mongodb/lib/server.js:274
      process.nextTick(function() { throw err; })
                                          ^
Error: collection name must be a String
    at Error (<anonymous>)
    at checkCollectionName (/home/shubham/node_modules/mongodb/lib/utils.js:69:11)
    at new Collection (/home/shubham/node_modules/mongodb/lib/collection.js:57:3)
    at /home/shubham/Music/pricesync/server/server.js:24:24
    at /home/shubham/node_modules/mongodb/lib/db.js:221:5
    at connectHandler (/home/shubham/node_modules/mongodb/lib/server.js:272:7)
    at g (events.js:180:16)
    at emit (events.js:95:17)
    at /home/shubham/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:399:23
    at /home/shubham/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:756:13

2 个答案:

答案 0 :(得分:0)

假设集合名称在'url'varialbe(即'urlinfo')中,实例化集合的正确方法是:

var collection = dbName.collection(url); //line 24

如果你看一下文档,它特别声明不应该直接实例化Collection类:https://mongodb.github.io/node-mongodb-native/api-generated/collection.html

答案 1 :(得分:0)

我遇到了同样的情况,同时解决了Guillermos Smashing Node.JS书中的练习......

我按照Richard Andreus的指示,经过几次尝试,成功建立了服务器。

我新定义了

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

而不是现有的变量定义。 接下来我已经定义了变量 db

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

然后打开与db的连接,或者在你的情况下打开dbName。

db.open(function(err, db) {
  var collection = db.collection(url);
// in my case I defined app.users instead of collection

注意:不要忘记您在dbName上的定义