How to use a MongoDB collection in another file - javascript

I have one server file that is server.js.
I have a MongoDB connection inside this file like this:
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
client.collection('userdetails',function(err,collection)
{
Ucollection=collection;
});
});
I have another file named server2.js. In this file I have to check if a username exists or not from Ucollection (this is collection name).
How can I give the MongoDB connection to server2.js? How can I use this collection in server2.js?

You could do something like this
in server.js:
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
global.mongoHelper = {};
global.mongoHelper.db = Db;
global.mongoHelper.bson = BSON;
global.mongoHelper.server = Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
client.collection('userdetails',function(err,collection)
{
Ucollection=collection;
});
});
in server2.js
client=new global.mongoHelper.db('database' , new global.mongoHelper.server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
client.collection('userdetails',function(err,collection)
{
Ucollection=collection;
});
});

I think much cleaner way of doing this is to seprate your database configration into seprate file. Like this
in database-config.js
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
module.exports.connectDatabase = function(callback){
client.open(function(err,pClient)
{
if(err){
console.log(err);
process.exit(1);
}
module.exports.userCollection = pClient.collection('userdetails');
callback();
});
}
in server.js
var database = require('./database-config')
database.connectDatabase(function() {
//here you can reuse collection like this
database.userCollection
}
in server2.js
var database = require('./database-config')
//here you can reuse collection like this
database.userCollection
I am assuming that server.js is your main file which actually intiate server so when you run your application it connects to database and load required collections which you can use anywhere in your application like I did this is considered as best practice to re-use collections. Let me know if there is any confusion

Well you are a bit mistaken about the whole concept of modularizing the code. For your task, you should not make a second server.js. You can make another module say, verifyUser and require it in your server.js file. You may require it (may be) after your mongodb connection.

server.js
var Db=require('mongodb').Db;
var BSON=require('mongodb').BSONPure;
var Server=require('mongodb').Server;
client=new Db('database' , new Server('127.0.0.1',27017),{safe:false});
client.open(function(err,pClient)
{
exports.Ucollection=pClient;
});
});
server2.js
var mongodb = require('mongodb');
var mainApp=require('./server');
var collectionObj=mainApp.Ucollection;
var collection = new mongodb.Collection(collectionObj, 'userdetails');
Using this collection.you can query like below
collection.insert(userInfo,{safe:true},function(err, objects) {
if(!err){
console.log('Data inserted successfully.');
}
});

Related

Cannot read property 'insert' of undefined when trying to put data in MongoDB

I'm getting this error: "Cannot read property 'insert' of undefined" when trying to insert data into a database. The error shows on:
db.coordinates.insert({ "x" : "data.x", "y" : "data.y"})
Database name - "node5"
Collection name - "coordinates"
// Including libraries
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var static = require('node-static'); // for serving files
//db connection
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/node5');
var url = 'mongodb://localhost:27017/node5';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server.");
db.close();
});
// This will make all the files in the current folder
// accessible from the web
var fileServer = new static.Server('./');
// This is the port for our web server.
// you will need to go to http://localhost:8080 to see it
app.listen(8080);
// If the URL of the socket server is opened in a browser
function handler(request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
}).resume();
}
// Delete this row if you want to see debug messages
io.set('log level', 1);
// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {
// Listen for mouse move events
socket.on('post', function (data) {
console.log('posted');
console.log(data);
socket.broadcast.emit('posted', data); // Broadcasts event to everyone except originating client
db.coordinates.insert({ "x" : "data.x", "y" : "data.y"})
});
});
When writing an answer, please note that I'm new to node.js and I might not understand if you tell the answer in a complex way:)
If you are using monk for your project, then you can drop the mongodb module, since it's functionality is being wrapped up by monk. From Monk's documentation, you should be doing something like:
const monk = require('monk');
const db = monk('localhost:27017/node5')
const coordinates = db.get('coordinates');
Now that you have a reference to your coordinates collection, you can use it later in your code:
coordinates.insert({ x: data.x, y: data.y });
I hope this is easy enough to understand. If it is still confusing, then please comment below and I'll elaborate further :)

Inserting Into A Mongodb Collection (Newbie)

I'm new to nodejs and mongodb. I'm trying to insert newClass into the class collection. Everything seems to be working except this function. It gives a 500 error and doesn't save the class.
I checked the mongodb docs and it seemed correct. Can someone please point me in the right direction?
routes
Class.createNewClass(newClass, function(err){
if (err){
console.log(err);
res.send(err);
} else {
console.log('Class saved.")
}
})
model
module.exports.createNewClass = function(newClass, callback){
Class.insert({newClass}, callback);
}
There's a syntax error in your createNewClass function, assuming the newClass variable is an object that contains all the key:value pairs you're saving to the new document, you should remove the curly braces:
module.exports.createNewClass = function(newClass, callback){
Class.insert(newClass, callback);
}
That said, the code you posted for your routes doesn't look much like a route to me, so there could be other errors your transcription is not revealing.
I'm not really clear on the overall structure of your app, but here is a very simple Express app that can insert new classes to the database.
var express = require('express');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var app = express();
app.use(bodyParser.json());
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/school", function(err, database) {
if(err) throw err;
db = database;
// Start the application after the database connection is ready
app.listen(3000);
console.log("Listening on port 3000");
});
app.post('/class', function(req,res) {
var collection = db.collection('classes');
var newClass = req.body;
console.log(req.body);
collection.insert(newClass);
res.json(newClass);
});
In your model change it to:
module.exports.createNewClass = function(newClass, callback){
Class.collection.insert(newClass, callback);
};
Check that "Class" should be schema model object.
module.exports.createNewClass = function(newClass, callback){
new Class(newClass).save(callback);
};
It's the basic mongoose way. In mongoose we use "insert" to multiple documents but you can also use insert for single document.

MongoDB : Read a file stored using GridFS from MongoDB in Javascript(using Node.JS)

In a mongodb from javascript code I am able to insert a file(of any extension) using gridfs, It's stored as fs.chunks & fs.files. Now i want to read this file's stream, but on any of the read opration calls on gridStore its giving error : "this.data.buffer.slice is not a function". I have used mongojs library from Node.JS.
// Write a file into MongoDB - Working fine.
// Our file ID
var fileId = new ObjectID();
// Open a new file
var gridStore;
// Create a file and open it
gridStore = new GridStore(db, fileId, "D:/Files/Sofa 2 N050210.3DS", "w+");
var data = fs.readFileSync('D:/Files/Sofa 2 N050210.3DS');
gridStore.open(function (err, gridStore) {
gridStore.write(data, function (err, gridStore) {
// Flush the file to GridFS
gridStore.close(function (err, fileData) {
// Write successfull
});
});
});
Now problem is when reading, After Closing gridStore, I tried to open file for reading & it is giving error at read call i.e on line no-4 in below code.
gridStore.close(function (result) {
var gridStore = new GridStore(db, "test_gs_seek_with_buffer", "r");
gridStore.open(function (err, gridStore) {
gridStore.read(5, function (err, data) {
if(err){
console.log("Error"); return;
}
console.log(data.toString());
});
});
});
Please help me find solution or the way to read back the file stored in GridFS (From the javascript code not from the command prompt).
This code is working fine for me. Try with this. Hope it works.
var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
mongoose.connection.once('open', function () {
gfs = new Grid(mongoose.connection.db, mongoose.mongo);//If you are using mongoose
});
var db = new mongo.Db('yourDatabaseName', new mongo.Server("127.0.0.1", 27017)); //if you are using mongoDb directily
var gfs = Grid(db, mongo);
var rstream = gfs.createReadStream(filename);
var bufs = [];
rstream.on('data', function (chunk) {
bufs.push(chunk);
}).on('error', function () {
res.send();
})
.on('end', function () { // done
var fbuf = Buffer.concat(bufs);
var File = (fbuf.toString('base64'));
res.send(File);
});

Send and get data with socket.io with an other javascript file nodejs and express

Lets say I have a JavaScript file that needs to communicate with other JavaScript file. So I could use this data in different javascript file.
In this case I have a game_server.js. In the gameserver.js I have two variables which I would like to use in the gamecore.js
var host // host of the game
var client // client that had joined the game
I would like to send them to the socket.io in de app.js and then use this variables in the game_core.js. So I can have data about the host and the client.
In the gamecore class i would like to have something like this
game_core.prototype.getPlayerInformation = function(data) {
this.host = data.host
this.client = data.client
}
It is all about getting information from the serverside to the clientside and the best way to do it is trough socket.io but i really don't know how
Also in the game_server script there is a instance for a game
game_server.createGame = function(player) {
//Create a new game instance
var thegame = {
id : UUID(), //generate a new id for the game
player_host:player, //so we know who initiated the game
player_client:null, //nobody else joined yet, since its new
player_count:1 //for simple checking of state
};
In the game_core the instance of a game is declared
var game_core = function(game_instance) {
//Store the instance, if any
this.instance = game_instance;
}
So it should be possible to get the player_host and player_client?
server.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
var Game_core = function(){}
Game_core.prototype.getPlayerInformation = function(data)
{
this.host = data.host
this.client = data.client
return {host: this.host, client: this.client}
}
var game_core = new Game_core()
io.sockets.on('connection', function (socket) {
socket.emit('login', game_core.getPlayerInformation);
});
client.js
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('login', function(data){
console.log(data); // {host: xx, client: xx}
})
</script>

Connection Pool for NodeJS

I have an app that has been maxing out the number of connection to MongoDB and I was under the assumption that if the drivers were set up correctly you didn't need to worry about closing connections.
I've seen people mention the Generic Pool module but what is the best process for closing or pooling connections using Node & MongoDB?
Here is my connection code for the app:
var sys = require("sys");
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
app.listen(1337);
io.configure(function () {
io.set('authorization', function (handshakeData, callback) {
callback(null, true);
});
});
function handler (req, res, data) {
sys.puts('request made to trackerapp.js');
res.writeHead(200);
res.end(data);
}
io.sockets.on('connection', function (socket) {
socket.on('adTracker', function (data) {
var adRequestData = data;
var databaseUrl = "mongodb://dbuser:dbpass#mongolab.com/tracker";
var collections = ["cmnads"]
var db = require("mongojs").connect(databaseUrl, collections);
db.cmnads.insert({adRequest : adRequestData},function(err, updated) {
if( err || !updated ) console.log("mongo not updated" + err);
else console.log("data stored");
});
});
});
After seeing JohnnyHK's comment I was able to pull the connection event out of the Socket.io connection and it worked fine, see the solution below:
var databaseUrl = "mongodb://dbuser:dbpass#mongolab.com/tracker";
var collections = ["cmnads"];
var db = mongojs.connect(databaseUrl, collections);
io.sockets.on('connection', function (socket) {
socket.on('adTracker', function (data) {
var adRequestData = data;
//vars for MongoDB used to be created here... so new connect function was called on every request to socket.io
db.cmnads.insert({adRequest : adRequestData},function(err, updated) {
if( err || !updated ) console.log("mongo not updated" + err);
else console.log("data stored");
});
});
});
A technique I used with my express apps that seems have some measure of success is to open a connection to a mongo instance (thereby getting a connection pool) then sharing that db (that is now in the "connected" state) instance wherever it is needed. Something like this:
server = new Server(app.settings.dbsettings.host, app.settings.dbsettings.port, {auto_reconnect: true, poolSize: 5})
db = new Db(app.settings.dbsettings.db, server, {native_parser:false})
db.open(function(err, db) {
app.db = db;
server = app.listen(app.settings.port);
console.log("Express server listening on port %d in %s mode", app.settings.port, app.settings.env);
require('./apps/socket-io')(app, server);
});
This connects to the database at the highest level in my app before the program moves into the wait listen state.
Before I used this pattern I would create a new database object whenever I needed to interact with the database. The problem I found is that the new database object would create a new thread pool, consuming a bunch of ports. These were never cleaned up properly. After a period of time the machine that hosted the app would run out of ports!
Anyway, a variation on the code I have shown should be where you should do your thinking I believe.

Categories

Resources