Using objectid can't retrieve data from MongoDB in Node.js - javascript

When I pass objectid of 1 hospital from Postman to this program it returns only empty array. But there is one data matching that objectid. Can you help me solve this? When I try to debug the program in console, I saw the array is empty.
doctor.js:
var express = require('express');
var router = express.Router();
var app=express()
var bodyParser = require("body-parser");
var validator = require('validator');
var mongo= require('./mongoconnect')
var authentication=require('./check_authentication')
var validate = require('./validation')
var ObjectId=require('mongodb').ObjectId
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.post('/',function(req,res)
{
if(validate.name(req.body.name) && validate.length(req.body.name) && validate.empty(req.body.name))
{
if(validate.empty(req.body.hospital_id))
{
mongo.find("hospital","_id",ObjectId(req.body.hospital_id),function(result1)
{
if(result1.length==1)
{
res.send("succcess")
}
})
}
}
})
module.exports = router;
And collection of MongoDB is:
hospital:
{
"_id" : ObjectId("5aa92df0ec6b3cc78ff88afd"),
"name" : "apollo_hospitals"
}
{
"_id" : ObjectId("5aa92df9ec6b3cc78ff88afe"),
"name" : "fortis"
}
mongoconnect.js:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
var dbo=null;
exports.connection=function()
{
if(dbo!=null) return
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
dbo = db.db("hospital_api");
});
}
var get = function (){
return dbo;
}
exports.find=function(collections,key,value,callback)
{
get().collection(collections).find({key:value}).toArray(function(err,result)
{
// console.log(collections)
// console.log(key)
// console.log(value)
if(err) throw err;
console.log(result)
callback(result)
})
}

Here, myself i got the solution.
We have to declare ObjectID with New keyword..
Var some_variable = New ObjectID(_id)
After that we can use that id anywhere using that some_variable

Related

Document is not deleting in MongoDB

I am using NodeJs and MongoDB as a backend service.I am trying to delete document on MongoDB but couldn't delete but sending response deleted.
This what I have done so far:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
var dburl = process.env.URL;
app.post('/deleteRow', (req,res) => {
MongoClient.connect(dburl,{useNewUrlParser:true}, (err,client) => {
var myquery = { _id:req.body.postId};
if(err){
console.log("Error:", +err);
}
else{
var collect = client.db('abc').collection('xyz');
collect.deleteOne(myquery, function(err,obj){
if(err){
console.log("Error".red, +err);
}
else{
res.send("Deleted");
}
});
}
});
});
Let me know what I need to correct in above code. Any help would be appreciated.
THANKS
Try casting your req.body.postId to an ObjectId
Something like
var ObjectID = require(‘mongodb’).ObjectID;
var postId = new ObjectID(req.body.postId);
Then use that postId in your deleteOne({}) params

mongodb not insert the full array

I use the following to insert 499 entry into a subdocument, I get the data from an array
my code is something like this (i will shortcut the array because it too long)
var bodyParser = require('body-parser');
var express = require("express");
var path = require("path");
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var app = express();
var url = "mongodb://<username>:<password>#ds157342.mlab.com:57342/heroku_4p9ggb81";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var entery = ['غبة خاتون','حي الربيع','المغرب','القاهرة','الصليخ',.........];
var collection = db.collection('customers');
for (var i = 0 ; i<entery.length; i++){
var query = {"_id" : ObjectId(),"value": entery[i],"key": i}
collection.updateOne({"_id":ObjectId("59ccdf34aabdd50011258cbf")},{ "$push": { "lookupdata": query }},{ upsert: true },
function (err, result) {if (err) throw err;db.close();
});
console.log(i + "- " + entery[i] + " add data finsh ");}
app.listen(process.env.PORT || 3000, function (){
console.log("server is started");});
my document structure like this
{
"_id" : ObjectId("59cce9fcaabdd50011258cc0"),
"formorder" : 1,
"isDisplayOnList" : true,
"issystemfield" : false,
"isMandatory" : false,
"description" : "-",
"labelname" : "name",
"displayname" : "name",
"fieldtype" : "list",
"formname" : "people",
"lookupdata" : [
{
"value" : "test",
"key" : "1",
"id" : "669c78c9-d086-442c-954b-d6d3f861664b"
}
],
}
my problem that my code does not insert all the 499 entry from the array into the "lookupdata" object, it just enters 50 entry and sometimes just 120 etc, I try to change the way I write this code many times but the problem still the same.
You are inserting/updating the data without using a callback, use async module.
`var bodyParser = require('body-parser');
var express = require("express");
var path = require("path");
var session = require('express-session');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var async = require('async');
var app = express();
var url = "mongodb://<username>:<password>#ds157342.mlab.com:57342/heroku_4p9ggb81";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var enteries = ['غبة خاتون','حي الربيع','المغرب','القاهرة','الصليخ',.........];
var collection = db.collection('customers');
async.eachOf(enteries, function(entery, key, callback){
var query = {"value": entery,"key": key}
collection.updateOne({"_id":ObjectId("59ccdf34aabdd50011258cbf")},{ "$push": { "lookupdata": query }},{ upsert: true },
function (err, result) {if (err) throw err;db.close();
});
}, function(err){
if(err) throw err;
});
console.log(i + "- " + entery[i] + " add data finsh ");}
app.listen(process.env.PORT || 3000, function (){
console.log("server is started");});`

Can't canonicalize query: IndexNotFound: text index required for $text query', code: 17287

The error is triggered in the Product.find statement below:
var bodyparser = require('body-parser');
var express = require('express');
var status = require('http-status');
var _ = require('underscore');
var mongoose = require('mongoose');
var productSchema = require('./product');
var schema = new mongoose.Schema(productSchema);
schema.index({ name: 'text' });
module.exports = function(wagner) {
var api = express.Router();
api.use(bodyparser.json());
api.get('/product/text/:query', wagner.invoke(function(Product) {
return function(req, res) {
console.log("we are in the get " + req.params.query);
Product.
find(
{ $text : { $search : req.params.query } },
{ score : { $meta: 'textScore' } }).
sort({ score: { $meta : 'textScore' } }).
limit(10).
exec(handleMany.bind(null, 'products', res));
};
}));
return api;
};
function handleMany(property, res, error, result) {
console.log("We are handling the many");
if (error) {
console.log(error);
return res.
status(status.INTERNAL_SERVER_ERROR).
json({ error: error.toString() });
}
var json = {};
json[property] = result;
res.json(json);
}
I'm running MongoDB 3.4.2 on windows 10. I explicitly ran the statement db.products.ensureIndex({name: "text"}); in the MongoDB shell and for the first time I didn't get the error. It still gets timeout errors intermittently, though, when the query takes more than 2000 ms. I thought that I didn't have to explicitly add an index in the MongoDB shell because I'm putting on a schema index in the above code, but I don't know for sure.
Thanks,
William
I got into the MongoDB shell and put the index on the products collection like this:
db.products.createIndex({name: "text"})
That was my solution, and it worked, but I don't know if there was a glitch somewhere that made that solution necessary.

Node js url shortener is looping rather than redirecting

I am writing a url shortener service in Node JS using mongo to connect to mLab.
Right now the user can send a request to the service with a url to shorten, and it returns a shortened url. However, if the user then sends the shortened url as a request, the redirect does not happen. Rather, the service goes into a loop.
1) How do I see what exactly is getting grabbed from the db? (Knowing how to do this would help out in trouble-shooting)
2) And what may be the cause of the looping issue?
var express = require('express')
var app = express()
var path = require('path');
var port = process.env.PORT || 8080;
var crypto = require("crypto");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({ // this schema is used for writing to the db
url : String,
key : String
});
var urlcntrctr = new Schema( // this schema is used for reading from the db
{ key: String, url : String, _id: String },
{ collection: 'urlcntrctr'}
);
const SchemaName = mongoose.model('SchemaName', urlcntrctr); // for reading from the db
app.get('/', (req, res, next) => res.sendFile(path.join(__dirname, '/index.html')) ) ;
app.set('port', (process.env.PORT || 5000));
app.get('/new/:url(*)', function(req, res) {
var shortenme = req.params[0];
var showme = req.params[0];
console.log("User's request: " +shortenme);
var amItrue = validateURL(shortenme);
if (amItrue){
connectmongoviamongoose();
var shortenmeObj = yncryptyyn(shortenme);
shortenme = shortenmeObj.key;
writeToDb(shortenmeObj); b
closetheconnection();
var contractedurl = 'http://firstappever-olddognewtrix123.c9users.io/' + shortenme;
var responseObject = ({"Original url: ": showme, "Contracted url: ": shortenme });
res.send(responseObject);
}
else{console.log("You need to enter a url, beginning with 'http' or 'https' and ending in '.com' or '.org' or whatever!");};
})
app.get('/:tag(*)', function(req, res) {
var targetnumber = req.params.tag;
sendforRedirect(req, res);
sendforRedirect(req, res);
})
function sendforRedirect(req, res){
var target = req.params.tag;
console.log("The value of target is " + target)
; var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>#ds159988.mlab.com:59988/urlcntrctr';
mongoose.connect(mongodbUri, options);
mongoose.Promise = global.Promise;
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("OK, you are connected for the redirect. ")
var query = {
key: {
$eq: target
}
}
SchemaName.find(query, function (err, doc) {
if(err){
console.log(err);
conn.close();
};
if(doc){
res.redirect(doc.url); // rather than redirecting, it is looping *****************
conn.close();
} else {
res.send("Sorry, we don't recognize that url");
conn.close();
}
});
});
}
function writeToDb(dataObject){
mongoose.model('Document', UserSchema);
var urlFromUser = mongoose.model('Document');
var urlfromuser = new urlFromUser();
urlfromuser.url = dataObject.url;
urlfromuser.key = dataObject.key;
urlfromuser.save();
};
function validateURL(textval) { //copied from http://stackoverflow.com/questions/1303872/trying-to-validate-url-using-javascript
var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*#)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
return urlregex.test(textval);
}
function connectmongoviamongoose(){
var mongoose = require('mongoose');
var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };
var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>#ds159988.mlab.com:59988/urlcntrctr';
mongoose.createConnection(mongodbUri, options);
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function() {
console.log("OK, you are connected. ")
});
}
function closetheconnection(){
var mongoose = require('mongoose');
mongoose.connection.close();
}
function yncryptyyn(incryptme){
var ulimit = 6;
var key = crypto.createHash('md5').update(incryptme).digest("base64");
key = key.slice(0,ulimit);
var obj = {
url: incryptme,
key: key
};
return obj;
}
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Better than console.log statements, you can use the package node-inspector to actually set breakpointsnin your code via chrome devtools and step through the code Much more robust process.
I would note that it is not clear to me what kind of urls you are shortening (internal to your site or external), but at present it looks like you're calling the redirect function twice, which should cause an error unto itself, and second if you are redirecting to internal urls your routes are probably going to match a lot that you don't want them to.
Finally, your code is kind of a jumble right now, which will make debugging harder no matter what you do. Try and break it out into different files based on what they do and test bits independently as much as possible.
For question 1: just put in a console.log, for example like this:
if(doc){
console.log(doc);
res.redirect(doc.url);
....
Even better put the whole functionality of the look up of the url into an own function, so you can check the working of the lookup and the working of the redirect independently.

Node.js REST with MySQL handle reconnect

I'm new to Node.js I followed tutorial from the internet for REST API with Node.js and MySQL. I can't get it to work after MySQL closes the connection or timeout occurs. Can you tell me how to modify my code to get it work:
Server.js
var express = require("express");
var mysql = require("mysql");
var bodyParser = require("body-parser");
var rest = require("./REST.js");
var app = express();
function REST(){
var self = this;
self.connectMysql();
};
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool({
connectionLimit : 50,
host : 'localhost',
user : 'root',
password : '',
database : 'quiz',
debug : false,
multipleStatements: true
});
pool.getConnection(function(err,connection){
if(err) {
self.stop(err);
} else {
self.configureExpress(connection);
}
});
}
REST.prototype.configureExpress = function(connection) {
var self = this;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var router = express.Router();
app.use('/', router);
var rest_router = new rest(router,connection);
self.startServer();
}
REST.prototype.startServer = function() {
app.listen(3000,function(){
console.log("All right ! I am alive at Port 3000.");
});
}
REST.prototype.stop = function(err) {
console.log("ISSUE WITH MYSQL n" + err);
process.exit(1);
}
new REST();
REST.js
var mysql = require("mysql");
function REST_ROUTER(router,connection) {
var self = this;
self.handleRoutes(router,connection);
}
REST_ROUTER.prototype.handleRoutes= function(router,connection) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
});
router.get("/quiz/cars",function(req,res){
var options = {sql: 'SELECT quiz.quiz_id, quiz_image, quiz_type, choice_id, choice, is_right_choice FROM quiz JOIN quiz_choices ON quiz.quiz_id = quiz_choices.quiz_id WHERE quiz_type="cars";', nestTables: false};
connection.query(options,function(err,rows){
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
res.json(rows);
}
});
});
}
module.exports = REST_ROUTER;
I have the same issue a and think this may be the solution. I made the following changes to my code:
Pass the connection pool rather than the connection to self.configureExpress() like so...
REST.prototype.connectMysql = function() {
var self = this;
var pool = mysql.createPool(db_config);
self.configureExpress(pool);
};
and
REST.prototype.configureExpress = function(pool) {
....
var rest_router = new rest(router,pool,md5);
....
}
REST.js
var mysql = require("mysql");
function REST_ROUTER(router,pool) {
var self = this;
self.handleRoutes(router,pool);
}
REST_ROUTER.prototype.handleRoutes= function(router,pool) {
router.get("/",function(req,res){
res.json({"Message" : "Hello World !"});
});
router.get("/quiz/cars",function(req,res){
var options = {sql: 'SELECT quiz.quiz_id, quiz_image, quiz_type, choice_id, choice, is_right_choice FROM quiz JOIN quiz_choices ON quiz.quiz_id = quiz_choices.quiz_id WHERE quiz_type="cars";', nestTables: false};
pool.getConnection(function(err, connection) {
connection.query(options,function(err,rows){
connection.release();
if(err) {
res.json({"Error" : true, "Message" : "Error executing MySQL query"});
} else {
res.json(rows);
}
});
});
});
}
module.exports = REST_ROUTER;
Don't forget to call connection.release(); after you've finished using the connection so that it can be added back to the connection pool.

Categories

Resources