Getting an object from MongoDB using its id - javascript

Let me explain my problem first.
I am trying to get the ID from URL and use it to find a record in the database(MongoDB). The following code I have in NodeJS Express App.
app.post('/dashboard/profile/update/:id',function(req,res){
var to_update=req.params.id;
var firstName=req.body.fname;
obj_to_search={_id:to_update};
db.open(function(err, dbs) {
if(!err) {
dbs.collection('project',function(err, collection) {
//update
collection.findOne(obj_to_search, function(err, result) {
if (err) {
throw err;
} else {
res.send(result);
}
dbs.close();
});
});
}
});
});
I am getting the record if I hard code the ID to 1. But I am not getting the record by this way. However I have checked using console.log the ID i am getting through URL is also 1.

Convert strings to integers
If a variable is in the url - it's a string. If you're wanting to query the database with a number, you'll need to cast it to a number for use in the query:
obj_to_search={_id: parseInt(to_update,10)};

Related

NodeJS MySQL Returning Empty Array When Passing Integers To Query

SECOND EDIT
The issue was caused by the MAX_INTEGER_VALUE which is lower then the integer value I was passing. I changed the MySQL table column to TEXT instead of BIGINT and everything is being returned correctly.
Thanks for all the help!
EDIT
So I just realized that the userID variable and the guildID variables are being passed using this line of code.
mysqlModule.userCrewSearch(575783451018526744, 282997056438665217);
However the values that are being supplied to the SQL statement turn the last two digits of the number into '00'. So instead of 575783451018526744 the value being passed into the SQL statement is 575783451018526700.
So why is this value being changed when nothing I am doing in my code is changing these values?
Original Post
I'll keep this short and sweet. I'm trying to run a query using the nodejs MySQL package. I'm not sure where I'm going wrong but whenever I call my function that executes my query, I'm always returned an empty array, unless I hardcode the values into the SQL query.
Heres the code:
// Search for the User's Crew
function userCrewSearch(guildID, userID) {
pool.getConnection(function(err, connection) {
if(err) {
return console.log(err);
}
var sql = "SELECT * FROM `crew-members` WHERE `userID`=? AND `guildID`=?;";
console.log(sql);
connection.query(sql, [guildID, userID], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) {
return console.log(err);
}
return console.log(results);
});
});
}
I'm calling this function like so: userCrewSearch(575783451018526744, 282997056438665217);
Both of the values I'm passing are integers. However this is what I get in my console.
However, here is my code with the values hardcoded into the SQL... to which the code then returns the result in the form of a RowDataPacket.
// Search for the User's Crew
function userCrewSearch(guildID, userID) {
pool.getConnection(function(err, connection) {
if(err) {
return console.log(err);
}
var sql = "SELECT * FROM `crew-members` WHERE `userID`=282997056438665217 AND `guildID`=575783451018526744;";
console.log(sql);
connection.query(sql, [guildID, userID], function(err, results) {
connection.release(); // always put connection back in pool after last query
if(err) {
return console.log(err);
}
return console.log(results);
});
});
}
Heres the result.
Bonus Question: How do I handle the RowDataPacket? Can I convert this directly into an object so I can call results.crewID and return just that value?
Same problem i was facing few days ago. I have solved this by converting the parameters into string.
function userCrewSearch(String(guildID), String(userID)) {
// your code here
}
Try adding + before your numeric parameter, it converts into number, it worked for me-
connection.query(sql, [+guildID, +userID], function(err, results) {
for your bonus questions answer, you can directly access the crewID or some other key using,
results[0].crewID
or do something like -
const [ result ] = results;
console.log(result.crewID)

Get an objects value by accessing and matching it's key value

I am retrieving an object with a database call, I want to access a key's value by matching that key with a variable that I have.
In my database return I get an object that looks similar to this:
{"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"}
I have a variable:
var intent = 'emailAddress'
The variable should always exist but theres a very slight chance it may not
and it may also be null.
What I want to do is access the value from that key field that matches the var intent, or at least get the key value pair.
What I also want to do is then if it is null then call an error, my full code is below:
getClientsDialog: function (domain, intent, callback) {
MongoClient.connect('mongodb://111011001101101', function (err, client) {
if (err) throw err;
var db = client.db('10001101');
db.collection('dialog').findOne({ domain: domain}, function (err, doc) {
// here I would want to say if (!err && ****logic to check match****)
if (!err) {
callback(doc)
} else {
throw err;
callback(err)
}
client.close();
});
console.dir("Called findOne");
});
}
Any help would be greatly appreciated!
Thanks!!
Not sure if i got the problem right but in ES6 you can use a computed value as an property name. Something like this:
let serverJson = {
"_id":"5c840d548a7db8af2f9eefea",
"domain":"chatbotdemo.com","deliveryTime":"ba",
"emailAddress":"ab","freeDelivery":"ab","onSale":"ab"
};
let intent = "emailAddress";
if (serverJson[intent]!== undefined) {
}
else {
}

How to implement query parameters in Postman with mongoose

I have a driver.js that contains a driver schema. Also the driverController.js, which contains my rest methods. GET, POST, DELETE, and PUT.
What i would like to do is
GET - http://localhost:3000/drivers?available=true
and have it return all of the drivers that are available.
My driver schema simply looks like this:
var mongoose = require('mongoose');
var DriverSchema = new mongoose.Schema({
name: String,
available: Boolean,
latitude: Number,
longitude: Number
});
mongoose.model('Driver', DriverSchema);
module.exports = mongoose.model('Driver');
I looked at some documentation, but I haven't been able to do anything.
Here's my GET method in which I'm attempting to add parameters
// GETS ALL DRIVERS FROM THE DATABASE
router.get('/', function (req, res) {
Driver.find({}, function (err, driver) {
if (err) return res.status(500).send("There was a problem finding the drivers.");
var available = req.query.available;
if (available == driver.available )
res.status(200).send(available );
else
res.status(200).send("Nice! " + driver.available);
});
});
This comparison doesn't ever work. It always goes to the else statement. I'm not quite sure why but the output is "Nice! undefined" Even though I have plenty of drivers in my database, and if I only put inside the else statement
res.status(200).send("Nice! " + driver);
Then it gives me the list of drivers.
Nonetheless, I would like to be able to use query parameters in order to find drivers.
Any hints or tips would be greatly appreciated, as this is a project and I have never worked with restAPI, or javascript before. Thanks!
NOTE: Mongoose, express. node.js, and mongoDB are being used.
if I only put inside the else statement res.status(200).send("Nice! " + driver); Then it gives me the list of drivers.
it's a list of drivers, with if (available == driver.available ) you're comparing a boolean with an array of objects,
instead of fetching all the drivers and checking if they have availabe == true , add the condition to the .find() and return the result :
// GETS ALL DRIVERS FROM THE DATABASE
router.get('/', function (req, res) {
Driver.find({ available : req.query.available }, function (err, drivers) {
if (err) return res.status(500).send("There was a problem finding the drivers.");
res.status(200).send(drivers);
});
});
EDIT :
you can do this to add filter depending on the query string :
// GETS ALL DRIVERS FROM THE DATABASE
router.get('/', function (req, res) {
var params = {};
Object.keys(req.query).forEach((v, k) => params[k] = v);
Driver.find(params, function (err, drivers) {
if (err) return res.status(500).send("There was a problem finding the drivers.");
res.status(200).send(drivers);
});
});
having ?name=Wario&available=true will create an object like { name : 'wario', available : true and pass it to the .find()

increment counter in node js mongodb

I want to make a counter of how many time the server js file has started, for my website using mongodb driver for angular js.
I want to save a varible named counter which has a value of 0 and then increment that value each time that the server is running. my code is below. as you can see my code doesn't acutally update the field in the db. just the varible.
beside that... well.. the whole code I wrote seems like bad practise. I basically have a document with {id:<>,count:0} and I am looping through all the count fields which are greater the -1 (i.e. integers) although I have only got just 1 count field.
isn't there any simple way to persist/get this 1 value from the db?
How can I update the field inside the db itself using something like $inc, in the easiest way possible?
Thanks
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
if (err) {
console.log(err);
}
else {
console.log("Connected correctly to DB.");
var dbusers =db.collection('users');
var cursor =dbusers.find( { "count": { $gt: -1 } } );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
doc.count=doc.count+1;
}
}
);
}
db.close();
});
Try this:
MongoClient.connect(url, function(err, db) {
if (err) {
console.log(err);
return db.close();
}
console.log("Connected correctly to DB.");
// update a record in the collection
db.users.update(
// find record with name "MyServer"
{ name: "MyServer" },
// increment it's property called "ran" by 1
{ $inc: { ran: 1 } }
);
return db.close();
});
This should be enough to get you started. It sounds like you're trying to do something like:
get me all the objects in the collection that have a property 'count' greater than -1
increase it's value by 1
save it to the collection.
The step you're missing is step 3. Doing it your way you'd have to do a bulk update. The example I gave you is updating a single record.
here is the documentation for increment. And here is the documentation for bulk updates.

Can't access all values of array

I am getting a row from mysql into an array using node-mariasql.
When I print this array out using my Winston logger, I get this:
steamid=76561198053558238, tradePartnerId=93292510, tradeToken=T3dZTnlq, autoSendWinnings=1, profilePrivacy=0, earnings=0.00, lastKnownName=jdK jdK, avatar=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c.jpg, avatarLarge=https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/49/4955f3be7e9b9d16e8fc0b16ed2407ba9b4c563c_full.jpg
If I print out the value for "steamid", I get this as a return:
76561198053558238
However, if I print out the value for "autoSendWinnnings" or "profilePrivacy", I get "undefined" as a return.
Why is that? What am I doing wrong? I don't think it is a MySQL related issue, because if I print out the whole array, I obviously get all values.
Still, I'll append the relevant code here.
statements['get_user'] = sql.prepare('SELECT * FROM `users` WHERE steamid=:steamid');
function getUser(steamid, callback) {
sql.query(statements.get_user({ steamid: steamid }), { useArray: true }, function(err, rows) {
if(err)
logger.error('A MySQL error occured: ' + err);
callback(rows);
});
}
getUser('76561198053558238' function(user) {
logger.debug(user); // I get the whole array here
logger.debug(user.steamid); // I get the value for steamid here
logger.debug(user.autoSendWinnings); // I get undefined here
});
Thanks in advance,
I hope someone can help me.
Your callback receives an Array of result rows. For reasons unknown said Array has a property steamid.
Try
getUser('76561198053558238', function(users) {
logger.debug(users);
logger.debug(users[0].steamid);
logger.debug(users[0].autoSendWinnings);
});

Categories