Error with java script while retrieving documents from mongodb - javascript

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

Related

get count collection with socket.io-mongodb

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

Node/Express Redirect After POST

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!

Node.JS query MongoDB returning null

I'am new to Node.js and MongoDB and I am trying it out.
I made a collection called footIco.
When I query MongoDB in the console with db.footIco.find(), it return all the data.
However when I query MongoDB from Node.js it doesn't return any data.
I can see the connection in MongoDB server console.
Here is my Node.js script;
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/footIco';
var findIco = function(db, callback) {
var cursor =db.collection('footIco').find();
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
console.dir(doc);
}
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
findIco(db, function() {
db.close();
});
});
Can anyone tell me what is wrong with this. It's pretty much a copy and paste from the MongoDB tutorial
This line:
assert.equal(err, null);
it is a JavaScript specific, that handlers that throws error will throw nowhere, I would recommend changing it to console.log(err) or just modify your callback to handle err parameter.

Nodejs Express MongoClient collection retrieval

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

nodejs mssql return recordset

Im trying to past the recordset from mssql request.query like a return value.
Following the code on https://www.npmjs.com/package/mssql is easy to make a a console output but when I try to asign the recordset to another variable doesnt work. What Im doing wrong?
var sql = require('mssql');
var config = {
user: 'sa',
password: 'XXXXXX',
server: '192.168.8.25',
database: '3TWIMDB',
}
var resultado='';
sql.connect(config, function(err){
var request = new sql.Request();
request.query('select 1 as VehiCLASS',function(err,recordset){
console.log(recordset[0].VehiCLASS);
resultado = recordset[0].VehiCLASS;
});
sql.close();
});
console.log("rsul: "+resultado);
Thanks.
The query is run asynchronously. console.log actually runs before resultado = recordset[0].VehiCLASS completes, so it's not set.
You must synchronize any code that relies on asynchronous operations. You have to do this by using the callbacks:
resultado = recordset[0].VehiCLASS;
console.log("rsul: ", resultado);
You may also specify your own callback function to prevent nesting:
function queryComplete(err, result) {
// should handle error
console.log("rsul: ", result);
}
resultado = recordset[0].VehiCLASS;
queryComplete(null, resultado);

Categories