2

I am trying to run following code on server

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);

but it gives following error while try to load 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

3 Answers 3

16

I had the same error, for me it was caused by my timestamp being incorrectly placed.


INCORRECT CODE:

    }),{timestamps:true});


CORRECTED CODE:

var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;

var User = mongoose.model('User', new mongoose.Schema({
    email:{type:String, required:true},
    password:{type:String, required:true},

    listings:[{type:ObjectId,ref:"Listings"}]

},{timestamps:true}));

Sign up to request clarification or add additional context in comments.

Comments

0

Assuming the collection name is in 'url' varialbe (i.e. 'urlinfo'), the right way to instantiate the collection would be:

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

If you look at documentation, it states specifically that Collection class should not be instantiated directly : https://mongodb.github.io/node-mongodb-native/api-generated/collection.html

1 Comment

Could you please elaborate more your answer adding a little more description about the solution you provide?
0

I got stuck at the same situation, while solving the exercise from Guillermos Smashing Node.JS book...

I followed Richard Andreus directions and after few attempts, succesfully established the server.

I newly defined

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

instead of existing variable definitions. As next I've defined the variable db.

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

Then open the connection to db, or in your case dbName.

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

NOTE: Don't forget your definition at dbName

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.