I am new to NodeJS. I am using NodeJS on server side. I am trying to make a simple REST based GET request which takes search parameter searchvar from user and returns the matching records found in a JSON array. My server code is as follows:
var express = require('express');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/mydb';
app.get('/search', function(req, res) {
res.set({ 'content-type': 'application/json; charset=utf-8' });
res.header("Content-Type", "application/json; charset=utf-8");
res.charset = 'utf-8';
var searchvar = req.query.searchvar;
if(searchvar != null) {
var recordsArray = new Array();
console.log("searchvar :: " + searchvar );
MongoClient.connect(url, function(err, db) {
var cursor = db.collection('myCollections').find({"name": new RegExp(searchvar)});
cursor.each(function(err, doc) {
//assert.equal(err, null);
if (doc != null) {
var tempObject = {"name": doc.name, "cat": doc.cat};
recordsArray.push(tempObject);
console.dir(doc);
} else {
db.close();
}
});
if(recordsArray.length > 0) {
console.log("if........");
res.json({"status": "SUCCESS", "message": "The request processed successfully.", "records":recordsArray});
} else {
console.log("else........");
res.json({"status": "FAILURE", "message": "No records found corresponding to given search query."});
}
});
} else {
res.json({"status": "FAILURE", "message": "The searchvar is missing."});
}
//res.send('id: ' + req.query.id);
});
app.listen(3000);
When I call it with RESTClient in a browser with following URL:
http://localhost:3000/search?searchvar=aa
I get following response:
{"status": "FAILURE", "message": "No records found corresponding to given search query."}
It is an async call. I want to know the process in server using which i can return the response when the processing is done and handle this async response on client side. Thanks in advance.