I'm trying to make a simple task.
In the first place, on client side, i'm sending data to server and then i insert these data into my mongodb database.
Then i try to get count of clients from my database.
var express = require('express');
var MONGO_URL = "mongodb://localhost:27017/mydatabase";
var app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongo = require('mongodb').MongoClient,
fs = require('fs');
var countUserSuscribed =0;
//here i insert data
/* Connection events */
io.on('connection', function (client) {
console.log("User connected");
client.on('InsertNewUser', function (newUser) {
console.log("we ar in InsertNewUser event");
//////////////////////////////////////////////////////////
mongo.connect(MONGO_URL, function (err, db) {
console.log("we are connected to mongodb");
var Users = db.collection('User');
console.log("on crée la collection et on fait l'ajout");
Users.insert({ player: myP }, function (err, o) {
if (err) { console.warn(err.message); }
else { console.log("user inserted into db: user"); }
});
});
})
});
//GET COUNT USER
console.log("here we get count user");
mongo.connect(MONGO_URL, function (err, db) {
countUserSuscribed = Users.count();
console.log("we got " + countUserSuscribed + " user in mongoDB");
});
With this code i can create collections and insert documents but the count function doesn't work and i didn't find much explanations on npm documentation.
Is it possible to use others mongodb functions than insert and collection with socket.io-mongodb ?
If it is, can someone give an example or explain me how to use it?
The count function works but is async function and takes a callback.
here's the fix:
countUserSuscribed = Users.count(function (err,c) { console.log(c) });
https://www.npmjs.com/package/mongodb-autoincrement consider using that. It keeps a track of all inserted document. Plus it has a handy feature to get the next count. Example let's say you inserted two records. If you call next count it will show 3. There fore to get the total documents inserted call get next count - 1. Make sense?
Sorry here is the correct one. https://www.npmjs.com/package/mongoose-auto-increment
Related
I use the following very basic script create a server:
var http = require('http');
var queryResult = '';
const PORT=8080;
function handleRequest(request, response){
fetchResult("user1"); //string is a placeholder, but works for now
setTimeout(function() {
// **POSSIBLE SOLUTION SPOT A**
response.end("some text");
}, 1000);
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){});
I've broken this up just because I think its easier to read. But on the same page I also the following:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
function fetchResult(query){
MongoClient.connect(url, function (err, db) {
if (!err) {
var collection = db.collection('users');
collection.find({name: query}).toArray(function (err, result) {
if (result.length)
queryResult = result;
// **POSSIBLE SOLUTION SPOT B**
db.close();
});
}
});
}
This works. It result is an object that has values from my database. And the server is able to write "some text" when someone makes a request. However, I can't get it so that the object is written onto the page or otherwise transferred when the user makes the request. What is the best way to do this?
Notes:
1) I know that using the timeout here is INSANELY bad. I couldn't figure out how to make the callback work properly and it works well enough for this example. I'll play through that myself issue once I solve the issue I've described above.
2) I think that JSON.stringify() may play a role in this, but I cant figure out what to do with it.
3) I don't want to use any other module (like express) just yet. I'm trying to understand how I would achieve the desired result with just the http module.
I think this is the Frankenstein code you're trying to write:
var http = require('http');
var mongodb = require('mongodb');
const PORT=8080;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
function handleRequest(request, response){
fetchResult("user1");
MongoClient.connect(url, function (err, db) {
if (!err) {
var collection = db.collection('users');
collection.find({name: query}).toArray(function (err, result) {
if (result.length)
response.end(JSON.stringify(result));
db.close();
});
}
});
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){});
As you said yourself, don't use this in production - it's a messy, unreadable blob. setTimeout has been removed because I'm not sure what you were trying to accomplish with it.
I have an Express post route which updates a mongo db based on data sent to it from a DataTables Editor inline field. So far so good and the database is updating fine. Where it falls over is after the update query executes successfully and I want to then redirect back to the originating page. The Node console seems to indicate that the GET route to the originating page is being called, but the page itself doesn't load.
The code for the POST function is as follows:
router.post('/edit', function(req,res){
var theKeys = _.keys(req.body);
var theMeat = theKeys[1];
var bits1 = theMeat.split("][");
// this is the updated value
var newVal = req.body[theMeat];
// this is the row _id
var cleanId = bits1[0].replace("data[row_","");
// this is the field to update
var cleanRow = bits1[1].replace("]","");
// cast the id string back to an ObjectId
var updId = new ObjectId(cleanId);
var query = {};
query[cleanRow] = newVal;
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/gts';
MongoClient.connect(url, function(err, db){
if(err){
console.log("Error connecting to the server", err);
}else{
//console.log("Connected for Edit");
var collection = db.collection('events');
collection.updateOne({"_id":updId},{$set:query},function(err,result){
if(err){
console.log("Error adding message", err);
}else if(result){
//console.log("Update attempted", result.result);
res.redirect('/admin');
}else{
console.log("Unknown error");
}
});
}
});
});
The GET route works fine when called directly, but seems to halt when called like this.
I'm pretty sure that there's nothing in the POST route that is causing this as the same thing happens when I strip out everything except the redirect itself.
router.post('/test',function(req,res){
res.redirect('/admin');
});
Please help!
I made node.js app that includes some REST services. Those services connect to a database (for example Oracle or DB2) to execute some query.
Since I'm a beginner in node.js programming, I have a question about my case:
What's the right way to access to a database? Is it better to have one connection reference while the app is running and use the same connection instance when REST services are called?
I found some examples that includes database connection in a separate module and use that module in app, something like that:
db2.js:
var db2 = require('ibm_db');
var db2ConnSettings = "DRIVER={DB2};DATABASE=mydb;HOSTNAME=localhost;UID=db2test;PWD=db2test;PORT=50000;PROTOCOL=TCPIP";
var db2Conn = db2.open(db2ConnSettings, function(err, conn) {
if (err)
return console.log(err);
});
module.exports = db2Conn;
server.js:
var express = require('express');
var app = express();
var db2Connection = require('./db2.js');
app.get('/data', function(req, res) {
console.log(db2Connection );
// make some query
});
When this service is called, db2connection is undefined. How come? How should I retrieve a db2 connection from db2.js file?
As said by #Sirko:
db2.js
var db2 = require('ibm_db');
var db2ConnSettings = "DRIVER={DB2};DATABASE=mydb;HOSTNAME=localhost;UID=db2test;PWD=db2test;PORT=50000;PROTOCOL=TCPIP";
var err, conn;
var callbacks = [];
module.exports = function(callback) {
// db2 module is called
if (err || conn) {
// connection has already been established
// (results of db2.open have been stored)
// callback immediately
callback(err, conn);
}
else {
// connection has not been established
// store the callback for when db connects
callbacks.push(callback);
}
};
db2.open(db2ConnSettings, function(_err, _conn){
// db has connected
err = _err; conn = _conn; // store results
var next_callback;
// array.pop() removed the last item from the array
// and returns it. if no items are left, returns null.
// so this loops through all stored callbacks.
while(next_callback = callbacks.pop()) {
// the removed item is stored in next_callback
next_callback(err, conn); // send connection results to callback
}
// no more items in callbacks to trigger
});
server.js
var express = require('express');
var app = express();
var db2Connection = require('./db2.js')(function(err, conn) {
// triggered if the connection has already been established
// or as soon as it HAS been established
app.get('/data', function(req, res) {
console.log(conn);
// ...
});
});
For Oracle with node-oracledb it's simple to create and use a connection pool. Your app would just get a free connection from the pool whenever it handles an HTTP REST request. Look at webapp.js and webapppromises.js in the examples. Node-oracledb has a 'connection pool queue' (see doc) which handles connection load spikes. It also has a 'connection pool cache' (also see the doc) which makes it easy to access a pool created in a different module.
I am converting my database connection to MongoClient and am having difficulty changing parts of my previous code over.
Previously, in order to retrieve all documents from a collection, I would use:
$.getJSON('/users/infolist', function(data) {
$.each(data, function(){
//cycles through each document and do whatever
});
});
which would call the following:
router.get('/infolist', function(req, res) {
var db = req.db;
var collection = db.get('empcollection');
collection.find({$query: {}, $orderby: {age:1}},{},function(e,docs){
res.json(docs);
});
});
After looking at documentation online, I still have not figured out how to replicate this behavior with MongoClient. I have established connection, and can query the database, but returning the collection, and cycling through each document as done above is not working.
Any advice or help would be greatly appreciated.
From your explanation, I understand that you want to use the native mongodb driver to retrieve a list of documents from your collection, update them using a loop, and then retrieving them to the client:
var MongoClient = require('mongodb').MongoClient;
//Establish a connection to your database
MongoClient.connect('mongodb://your/connection/string', function(err, db) {
if(err) {
console.log('There was an error connecting to the database');
}
//Map empcollection to a variable
var collection = db.collection('empcollection');
//Query the collection and retrieve the documents in an array
collection.find({}).toArray(function(err, docs)) {
if(err) {
console.log('There was an error retrieveing the matched documents');
}
//Loop through the documents and change them accordingly
for(var i = 0; i < docs.length; i++) {
//........
}
//Retrieve the updated data
res.json(docs);
}
});
});
Basically the idea is to get documents by calling a function from MongoDB using JavaScript (not Node.js)
var mongo = require('mongodb');
mongo.MongoClient.connect('mongodb://localhost:27017/Database',function(err,db)
{
var result = [];
result = db.eval('getContacts("_id")',function(error, result)
{
console.log("Error is:" +error);
console.log("result is:"+result);
console.log("working till here");
})
// db.close();
});
note: getConatcts is a DB function to get contact related details.
Error: Error is:null
result is:
working till here