I've been trying to make a simple site with Node.js, Express.js, and MongoDB. I'm new to these technologies and have been having problem set up the database
Here is snippet of code in my index.js file:
var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver;
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var mongoHost = 'localHost';
var mongoPort = 27017;
var collectionDriver;
var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));
mongoClient.open(function(err, mongoClient) {
if (!mongoClient) {
console.error("Error! Exiting... Must start MongoDB first");
process.exit(1);
}
var db = mongoClient.db("MyDatabase");
collectionDriver = new CollectionDriver(db);
});
After I try to run node index.js in terminal, it says the following:
js-bson: Failed to load c++ bson extension, using pure JS version
/Users/username/dev/ga-final/index.js:31
mongoClient.open(function(err, mongoClient) { //C
^
TypeError: Object #<MongoClient> has no method 'open'
at Object.<anonymous> (/Users/username/dev/ga-final/index.js:31:13)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
What is wrong? Why can't I call open? Can you help me fix this? thanks!
This is happening may be because you are using new version of mongodb it is working fine after I use mongodb driver version 1.4.
npm install mongodb#1.4.x
Take a look at the mongodb docs. Your mongoClient object is not what you think it is, and that why there isn't an open() method available.
Make your example code look more like theirs:
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();
});
Related
Nothing seems to work except the "throw new Error" in my code, I have installed all the necessary packages I'm sure. I am getting no errors in other places of my code. I can't seem to find the problem. Hoping someone knows how to solve this.
const express = require('express'); // we're making an ExpressJS App
const bodyParser = require('body-parser'); // we'll use body-parser extensively
//const port =3000
const app = express(); // create the ExpressJS app
// parse the different kinds of requests (content-type) the app handles
// use the "use" method to set up the body-parser middlewear
app.use(express.json()) // application/json
app.use(express.urlencoded({ extended: true })) // application/x-www-form-urlencoded
// Set up Mongoose and our Database connection
const dbConnect = require('./config/AtlasConnect.js');
const mongoose = require('mongoose');
// Set up connection to the database
mongoose.connect(dbConnect.database.url, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log("Successfully connected to the MongoDB database");
}).catch(err => {
console.log('Unable to connect to the MongoDB database', err);
process.exit();
});
throw new Error("NOT WORKING!");
// // create our test route (reply by sending a JSON message as response)
// app.get('/', (req, res) => {
// res.json({"message": "My Phone Shop App. Use the app to manage your favourite s!"});
// });
require('./app/routes/Users.routes.js')(app);
// listen for requests on port 3000
app.listen(3000, () => {
console.log("Server listening on port 3000");
});
This is the error I get in terminal:
PS C:\Users\jaffe\Documents\assignment-06-17518623> node assignment-06.js
C:\Users\jaffe\Documents\assignment-06-17518623\assignment-06.js:44
throw new Error("NOT WORKING!");
^
Error: NOT WORKING!
at Object.<anonymous> (C:\Users\jaffe\Documents\assignment-06-17518623\assignment-06.js:44:7)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
Line throw new Error("NOT WORKING!"); always throws exception, and stops code execution.
See documentation https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Statements/throw
Sorry if i'm ignorant or there is an actual problem here. I am hosting a http server with node.js, and apon running the server I get the error
C:\Users\Xander\Desktop\Website>node ./processes.js
C:\Users\Xander\Desktop\Website\node_modules\socket.io\node_modules\engine.io\lib\server.js:
var listeners = server.listeners('request').slice(0);
^
TypeError: Cannot read property 'listeners' of undefined
at Server.attach
(C:\Users\Xander\Desktop\Website\node_modules\socket.io\node_modules\engine.io\lib\server.js:423:25)
at Function.attach (C:\Users\Xander\Desktop\Website\node_modules\socket.io\node_modules\engine.io\lib\engine.io.js:124:10)
at Server.listen.Server.attach (C:\Users\Xander\Desktop\Website\node_modules\socket.io\lib\index.js:228:21)
at Object.<anonymous> (C:\Users\Xander\Desktop\Website\processes.js:8:21)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
This error has not occurred before and just recently came up. I've tried reinstalling socket.io, and personally editing the file. Though, to no avail. It fails every time. So i'll gladly take advice on how to fix this. Thank you for your time...
How its being used
//Vars
var http = require('http');
var express = require("express");
var app = express();
var path = require("path");
var connect = require("connect");
var io = require('socket.io').listen(server);
var socket = io.listen(server);
//Defined port
const PORT = 8080;
//Connection handler
function handleRequest(request, response){
response.end(request.url);
};
var server = http.createServer(handleRequest);
//Log all connections made
//Show .html file
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/index.html'));
});
//Port to listen to
app.listen(8080);
In this line of your code:
var io = require('socket.io').listen(server);
server is undefined.
You can probably change this:
app.listen(8080);
to this:
var server = app.listen(8080);
var io = require('socket.io').listen(server);
And, get rid of these that are too early in your code:
var io = require('socket.io').listen(server);
var socket = io.listen(server);
And, remove these too since you're using Express as your server:
function handleRequest(request, response){
response.end(request.url);
};
var server = http.createServer(handleRequest);
I am getting the following error while trying to run server using Node.ja with Mongodb.
Error:
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
C:\xampp\htdocs\odiya_chat\server.js:15
db = mongo.connect("127.0.0.1:27017/"+db, collections);
^
TypeError: Object function (connString, cols) {
var dbname = getDbName(connString);
var onserver = thunky(function(cb) {
getTopology(connString, function(err, topology) {
if (err) return cb(err);
cb(null, topology);
});
});
if (!dbname) {
dbname = connString._dbname;
onserver = thunky(function(cb) {
toMongodbCore(connString, function(err, server) {
if (err) cb(new Error('You must pass a connection string or a mongojs in
stance.'));
cb(null, server);
});
});
}
var that = new Database({name: dbname, cols: cols}, onserver);
if (typeof Proxy !== 'undefined') {
var p = Proxy.create({
get: function(obj, prop) {
if (that[prop]) return that[prop];
that[prop] = that.collection(prop);
return that[prop];
}
});
return p;
};
return that;
} has no method 'connect'
at Object.<anonymous> (C:\xampp\htdocs\odiya_chat\server.js:15:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
Error-2
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
{ [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' }
js-bson: Failed to load c++ bson extension, using pure JS version
My server side code is given below.
Server.js
var port=8888;
var express=require('express');
var http=require('http');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var mongo = require('mongojs');
var app=express();
var server=http.createServer(app);
db = 'doctor',
collections = ['oditek'],
db = mongo.connect("127.0.0.1:27017/"+db, collections);
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: false })) // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) // parse application/json
app.use(methodOverride());
app.use(cookieParser());
//app.use(expressSession({secret:'somesecrettokenhere'})); // simulate DELETE and PUT
app.get('/',function(req,res){
res.sendfile('view/index.html');
})
app.get('/login',function(req,res){
res.sendfile('view/login.html');
});
app.get('/chatroom',function(req,res){
if(req.session){
res.sendfile('view/chatroom.html');
}
});
server.listen(port);
console.log('server is running on the port'+port);
Here My requirement is If user is already logged in client side he will get the chatroom.html page and if not in client side it will ask you for login.I am implementing here connect-mongodb-session for store the session.I have read some posts regarding this and tried the answer but still error was there.Please help me to resolve this error.
Since you're using the mongojs module, you're going to have to connect to the database using the following method
db = mongo("127.0.0.1:27017/"+db, collections);
I am trying to get socket.io running with node/express (I have done this countless times - so I am pretty baffled). When I try to configure socket.io with the io.configure method I get an error:
io.configure(function() {
^
TypeError: Object #<Server> has no method 'configure'
at Object.<anonymous> (/home/yz/webdev/ground/app.js:377:4)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
My code is exactly how it says to do it on socket.io - but I'll post it just in case:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
//other declarations
app.use(...
passport.use(...
//some routes
app.get(...
app.post(...
io.configure(function() {
io.set('transports', ['websocket','xhr-polling','flashsocket']);
io.set('flash policy port', 10843);
});
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
...
});
});
The error gets thrown at the io.configure method - I have done this before with other sites, I don't understand whey it isn't working now. Thanks.
UPDATE
I was just reading here that io.configure doesn't exist anymore - however, I can't seem to get it working the new way either. Here is my new code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
//var io = require('socket.io').listen(server);
var socket = require('socket.io')({
'transports': ['websocket','xhr-polling','flashsocket'],
'flash policy port': 10843
});
var io = socket.listen(server);
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
...
});
});
I'm not getting any errors, socket.io just doesn't seem to be starting.
You're assigning io to a server, which is causing the problems when you attempt to call functions on io which are available from socket.io. Try replacing this line:
var io = require('socket.io').listen(server);
With this line:
var io = require('socket.io')(server);
The socket.io docs list a couple of configuration patterns you can take advantage of, and it is possible to create a server using socket.io. But since you're already creating a server, you shouldn't need to do it with socket.io.
I'm trying to get started with the MEAN stack. And I'm following this tutorial: link
I have made it until the Test Our Server section. Here
// modules =================================================
var express = require('express');
var app = express();
var mongoose= require('mongoose');
// configuration ===========================================
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
mongoose.connect(db.url); // connect to our mongoDB database (uncomment after you enter in your own credentials in config/db.js)
app.configure(function() {
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(express.logger('dev')); // log every request to the console
app.use(express.bodyParser()); // have the ability to pull information from html in POST
app.use(express.methodOverride()); // have the ability to simulate DELETE and PUT
});
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
app.listen(port); // startup our app at http://localhost:8080
console.log('Magic happens on port ' + port); // shoutout to the user
exports = module.exports = app; // expose app
When I run
nodemon server.js
I get this error
app.configure(function() {
^
TypeError: Object function (req, res, next) {
app.handle(req, res, next);
} has no method 'configure'
at Object.<anonymous> (C:\Users\Yuksel\Desktop\node\test\server.js:14:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
5 Mar 17:27:20 - [nodemon] app crashed - waiting for file changes before startin
g...
It simply says app has no method configure(I guess). But when I delete the configure part and run it again, it works.(This mean app has .listen method, so it is an express object.)
I have tried with both node and nodemon. And I couldn't figure it out. Thank you for your time.
Tom in his blog post new-features-node-express-4 provides examples of how to convert from using app.configure in express version 3.x to removing it in express version 4.0.
For convenience I added the code example below.
Version 3.x
// all environments
app.configure(function(){
app.set('title', 'Application Title');
})
// development only
app.configure('development', function(){
app.set('mongodb_uri', 'mongo://localhost/dev');
})
// production only
app.configure('production', function(){
app.set('mongodb_uri', 'mongo://localhost/prod');
})
Version 4.0
// all environments
app.set('title', 'Application Title');
// development only
if ('development' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/dev');
}
// production only
if ('production' == app.get('env')) {
app.set('mongodb_uri', 'mongo://localhost/prod');
}
The configure method has been removed from express as of version 4.0.0 (including 4.0.0-rc2). See the changelog at https://github.com/strongloop/express/blob/master/History.md#400--2014-04-09