How to query in nodejs? - javascript

this is my first time asking questions and this is basically my last resort in finding some answers. Im a noob and beginner in javascript so please use simple terms with me.
So i have an issue. I dont know how to query.
- As in do i put all my queries in one script or do i have to split them up to different scripts.
- Right now, i have a server.js and i put all my codes in there. including queries. So how do i run just one of them.
- and also if there is such a thing for me to query for just another number like 4. Do i have to go back to the script to manually change from '110' to '4' or can i just enter it somewhere.
Some examples are:
//length of 110
db.collection.find({length: "110"}, function(err, collection) {
if( err || !collection) console.log("No collections with 110 in length");
else collection.forEach( function(length) {
console.log(length);
} );
});
//shows record of length 110 and length 340
var length = ['110', '340']
length = length.join('|');
var re = new RegExp(length, 'i')
db.collection.find({length:{$regex: re}}, function(err, collection) {
if( err || !collection ) console.log("User not found");
else collection.forEach (function(length){
console.log(length);
});
});
How do i query to only run for one of them in mongodb. Appericiate the help alot guys

You already know that node.js is used for making servers. So there are 2 ways you can query the database. Since you're new to node, I'm going to list both the ways :
1.A http GET for querying data (Standard Way)
You can write a simple http server and set a route for getting the type of data you want.I've written a small file so that you can understand:
var express = require('express');
var http = require('http');
var app = express();
var bodyParser = require('body-parser');
// Db settings
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
function getConnection(url, callback) {
MongoClient.connect(url, function(dbErr, dbRes) {
if(dbErr) {
return callback(err, null);
}
callback(null, dbRes);
});
}
// Configure app to use bodyparser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = process.env.PORT || 7013;
app.set('port', port);
app.use(function(req, res, next) {
console.log(req.ip+ ":"+port + req.url + " "+req.method);
next();
});
app.get('/getCityData', function(req, res, next) {
var cityName = req.query.city;
getConnection(url, function(conErr, db) {
if(conErr) {
return res.send("ERROR IN GETTING connection");
}
var cityCollection = db.collection('cities');
cityCollection.find({"city":cityName}).toArray(function(err, result) {
if(err) return res.send("error in querying data");
db.close();
res.send(result);
});
});
});
var httpServer = http.createServer(app).listen(port, function() {
console.log("Express server listening on port "+app.get('port'));
});
You can query the server using curl or postman like this :
2.Using command line arguments :
You can also do it the easy way using command line arguments by passing the parameter to query, but it's less flexible:
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/my_database_name';
function getConnection(url, callback) {
MongoClient.connect(url, function(dbErr, dbRes) {
if(dbErr) {
return callback(err, null);
}
callback(null, dbRes);
});
}
var cityName = process.argv[2]; // that's the argument you'd receive
getConnection(url, function(conErr, db) {
if(conErr) {
return res.send("ERROR IN GETTING connection");
}
var cityCollection = db.collection('cities');
cityCollection.find({"city":cityName}).toArray(function(err, result) {
if(err) return res.send("error in querying data");
db.close();
console.log(result);
});
});
Pass that commandline argument like this while executing file :
I hope it helps

Related

Mongodb Nodejs: return undefined after callback of an exported function

I'm new to the Node.js world. I've connected node to my MongoDB server. Now I want to write my module for MongoDB's CRUD operations but when I call find, it returns undefined.
How can I solve this problem?
main.js
var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
var url = "mongodb://localhost:27017/movie";
var result;
var crud = require('./crud.js');
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("movie");
var test=crud.findAll(db,dbo,"test");
console.log(test);
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Listening on "+host+":"+port);
})
crud.js
exports.findAll = function(db, dbo, collection){
dbo.collection(collection).find({}).toArray(function(err,result){
if (err) throw err;
db.close();
return result;
});
}
The function findAll is not returning a value for that reason the value of test is undefined. You have to deal with the callback result or do an implementation based on Promise.

Sending MongoDB results with Node

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.

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.

How to create New MongoDb Database using the Node JS driver

I want to create a new Database in MongoDB using the Node JS driver. I tried the following approaches, but none of them created any databases (I checked using the mongo shell and RoboMongo) and the worst part is, it is not showing any errors, below programs are executed successfully without any error (I mean, error is NULL)
First Method, using the Mongo Server
var Db = require('mongodb').Db,
Server = require('mongodb').Server;
var db = new Db('myNewDatabase', new Server('localhost', 27017));
db.open(function (err, db) {
if (err) {
console.dir('ERROR we are in the callback of the open ');
console.dir(err);
throw err;
}
// Use the admin database for the operation
var adminDb = db.admin();
console.dir('we are in the callback of the open');
db.close();
});
Second approach I followed is:
var server = "localhost";
var port = 27017;
var dbName = "myNewDatabase";
var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var connString = "mongodb://"+server+":"+port+"/"+dbName;
mongoClient.connect(connString, function(err, db) {
console.dir(err);
if(!err) {
console.log("\nMongo DB connected\n");
db.collection('test_correctly_access_collections', function(err, col2) {
console.dir(err);
if(err) {
console.dir('Thier is a error in creating collection');
console.dir(err);
}
console.log("\nColllection created succesfully\n");
db.close();
});
}
else{
console.log("Mongo DB could not be connected");
process.exit(0);
}
});
According to this link, we can use getDatabase API to create a new database, i tried for the same API in the Node JS, but i am unable to find one.
As searched in google and stackOverflow for this question, but I am able to find, only very few. So i am posting the answer to this myself.
At first thank you #somallg , you are right i voted up your comment.
Answer is, you need to insert document into collection and then, MongoDB will create the New Database and also the collection. So, above approaches in my question can we re-written as follows to create a new database using the Node JS Driver:
First Appoarch
var Db = require('mongodb').Db,
Server = require('mongodb').Server;
var db = new Db('myNewDatabase', new Server('localhost', 27017));
db.open(function (err, db) {
if (err) {
console.dir('ERROR we are in the callback of the open ');
console.dir(err);
throw err;
}
var collection = db.collection("simple_document_insert_collection_no_safe");
collection.insert({hello:'world_no_safe'});
console.dir('we are in the callback of the open');
db.close();
});
second approach
var server = "localhost";
var port = 27017;
var dbName = "myNewDatabase";
var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var connString = "mongodb://"+server+":"+port+"/"+dbName;
mongoClient.connect(connString, function(err, db) {
console.dir(err);
if(!err) {
var collection = db.collection("simple_document_insert_collection_no_safe");
collection.insert({hello:'world_no_safe'});
}
else{
console.log("Mongo DB could not be connected");
process.exit(0);
}
db.close();
});

How to return JSON from MongoDB in Node.js?

I have a mongodb database called pokemon with a collection called pokemons. Here is my attempt to write a function that will do a find() operation in mongodb:
'use strict';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// db url
var url = 'mongodb://localhost:27017/pokemon';
exports.getPokemonByName = function (name) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('pokemons').find({name: name});
// how to return json?
});
};
I then call this function in another file:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName('Dratini'));
})
This link is helpful in showing how to log mongodb data to the console by doing some sort of each() method on the cursor object, but I don't know how to return json through the getPokemonByName function. I tried to define an empty array on the root scope of the getPokemonByName function and push data into that array with each iteration of the .each method show in that link, but I think I still can't return that array because it happens after the fact.
BTW, I'm really just doing this for fun and to learn about MongoDB and Node.js, so I don't want to use or an ODM like Mongoose to do some of this work for me.
I was able to answer my question with help from node's native monogodb driver github page: See here.
In essence, what I did was to define my exported function within the MongoClient's connection function. For some reason I thought node exports had to be in the root of the module, but that's not the case. Here's a finished version:
'use strict';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
// db url
var url = 'mongodb://localhost:27017/pokemon';
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('pokemons');
// Find some documents
collection.find({name: 'Dratini'}).toArray(function(err, docs) {
assert.equal(err, null);
// assert.equal(2, docs.length);
console.log("Found the following records");
callback(docs);
});
}
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
findDocuments(db, function(docs) {
console.log(docs);
exports.getPokemonByName = function() {
return docs;
}
db.close();
});
});
And then in another file:
var express = require('express');
var router = express.Router();
router.get('/pokedex', function (req, res) {
res.jsonp(db.getPokemonByName());
});
Of course, this solution requires that I hardcode queries, but I'm okay with that for now. Will cross that bridge when I come to it.
Found a simple tweak for this. Let say the callback to the findOne returns result then you can convert the result to JSON object like this
result = JSON.parse(JSON.stringify(result))
Now you can access the result and its fields simply with the dot operator.
this may help
var cursor = db.collection('pokemons').find({name:name}).toArray(function(err,arr){
return arr;
});
You can use callbacks on find function to return the json.
Try
exports.getPokemonByName = function (name,callback) {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('pokemons').find({name: name},function(err,result){
if(err)
{
callback(err,null);
}
if(result)
callback(null,result);
});
});
};
router.get('/pokedex', function (req, res) {
db.getPokemonByName('Dratini',function(err,result){
if(result)
{
res.jsonp(result);
}
});
})

Categories