How to get user info from mongodb in node.js - node.js

Totally new to mongo, I've been checking examples for hours, Trying to check if a user exists in this collection:
{ "name" : "chrispy", "pass" : "xxxx", "_id" : ObjectId("5221b29b69f9e9b11a000001") }
But cannot match name and get the results, i've tried numerous examples, and no luck.
Works well in the console:
mongo main
> db.users.findOne({name : 'chrispy'})
{
"name" : "chrispy",
"pass" : "xxxx",
"_id" : ObjectId("5221b29b69f9e9b11a000001")
}
>
Once I can match the name, I'll match the password. but cant even get as far as matching the user name. Help = 1000 thankyou's!
var name = 'chrispy';
var pass = '';
console.log("About to check for name and pw");
Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
if(err) throw err;
var collection = db.collection('users');
// does user exist
var doc = collection.findOne({name : name}, function(err,doc){
if(err) throw err;
if(doc)
console.log("1 Found: "+name+", pass="+doc.pass);
else
console.log("1 Not found: "+name);
});
if(doc)
console.log("2 Found: "+name+", pass="+doc.pass);
else
console.log("2 Not found: "+name);
db.close();
});
Console Output:
About to check for name and pw
2 Not found: chrispy
It doesn't even seem to be going in to the findOne() function, external to the findOn() function it fails anyway.

So here are the changes before it started to work, removed var Doc = , and closed the db only after function within findOne() is fired, else it closes the DB before the result.
var name = 'chrispy';
var pass = '';
console.log("About to check for name and pw");
Mongo.connect('mongodb://127.0.0.1:27017/main', function(err, db) {
if(err) throw err;
var collection = db.collection('users');
// does user exist
collection.findOne({name : name}, function(err,doc){
if(err) throw err;
if(doc)
console.log("Found: "+name+", pass="+doc.pass);
else
console.log("Not found: "+name);
db.close();
});
});

Just to be clear, the various database calls are asynchronous actions that utilize Javascript Promises. The call to findOne returns a Promise object, not the found document. That is,
collection.findOne(
{name: name},
function(err,doc) {
/* handle err or process doc */
}
);
is functionally equivalent to
collection.findOne(
{name: name}
).then(
// resolved handler
function(doc) {
// process doc
},
// rejected handler
function(err) {
// handle err
}
);
Your code was starting the asynchronous findOne call and then closing the database before the call has finished (i.e. the promise resolved or rejected). If you need to close the db, you should do it in the callback, once you've obtained your document.

Related

getting specific item from query answer mongodb node

I was wondering if there is a way I can get a part of an object in mongo using node. For example, it would be great if I could log say the email that is being added, by using something like console.log(result.email) to get the email part of my response. Does anyone know how to do this?
Ok so I have found a way to do this. It will not work on the .find function for some reason, but will work on .findOne and .sort
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("db");
let query = {
username: "username",
key: "key"
};
dbo.collection("keys").findOne(query, (function(err, result) {
var lengthboi = result.length;
console.log(result)
if (lengthboi === 1) {
//do stuff
} else {
}
}));
});

MongoError : selector must be a valid JavaScript object

I am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})
You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.

Mongoose / Mongodb update return value and error handling

I am a little confused about the return value of Mongoldb update and how should I handle error with it.
I am using Node.js, Express.js and Mongoose.js as my Mongodb driver
As I look through many tutorial, the only way of error handling I saw is ...
Example: A simple user schema .. and I want to update telephoneNumber
Users
{
email : abc#abc.com,
telephoneNumber : 123456
}
Example of error handling written in node.js that many tutorial taught me
Users.update({email: abc#abc.com}, {'$set': {telephoneNumber : 654321}, function(err, result){
if(err){
//err
}else if(!result){
//update not success
}else{
//update success
}
});
but as I look through Mongodb documentation, I found out that update return WriteConcern value, which return something like this
{
"ok" : 1, // update with no err
"nModified" :1, // successfully update 1 user
"n" : 1 // found 1
}
So my question is, should I handle my error like this instead, so I would know more about the failures of update...
Users.update({email: abc#abc.com}, {'$set': {telephoneNumber : 654321}, function(err, result){
if(err || result.ok === 0){
//err
}else if(result.nModified === 0){
//update fail
}else if(result.n === 0){
//could not be found
}else{
//update success
}
});
Is this a bad approach to update handling in mongoose/mongodb?
Thanks!! :)
Here is how we handle mongoose/mongodb errors. They might be errors like "that value already exists" Or similar issues.
First in the error block of the mongoose call we add:
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err,req,res)
});
}
Which calls a 'getErrorMessage' function which is defined in our errorHandler file, which might call the unique error message function. We also log the errors in our mongo database under a separate collection.
exports.getErrorMessage = function(err,req,res) {
var message = '';
if (err.code) {
switch (err.code) {
case 11000:
case 11001:
message = getUniqueErrorMessage(err);
break;
default:
message = 'Something went wrong. We have logged this issue and will correct';
}
} else {
for (var errName in err.errors) {
if (err.errors[errName].message) message = err.errors[errName].message;
}
}
//log the error to Mongo
ErrorLog.create(err,req,res);
return message;
};
var getUniqueErrorMessage = function(err) {
var output;
try {
var fieldName = err.err.substring(err.err.lastIndexOf('.$') + 2, err.err.lastIndexOf('_1'));
output = fieldName.charAt(0).toUpperCase() + fieldName.slice(1) + ' already exists';
} catch (ex) {
output = 'Unique field already exists';
}
return output;
};
Hope that helps, let me know if I can clarify anything.

node js mongo find last inserted

I am having a hard time trying to find the last inserted element into mongo. I am using an example code I found and trying to make the query and display the item but I am getting an error. I understand I am suppose to do something like this.
db.collectionName.findOne({}, {sort:{$natural:-1}})
But this is what I have so far and it's not working.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
collection.insert(doc1);
collection.insert(doc2, {w:1}, function(err, result) {});
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
collection.find({}).toArray(function(err, docs) {
console.log(docs[0]);
});
db.close();
});
This is the error.
nodejs/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
TypeError: Cannot read property '0' of null
I checked to make sure the database is not empty so I am not sure why it's returning null.
I've found a possible solution(here) to your problem. It might be due to the fact that the database connection closes before the operations that you have issued finish.
You can fix it by including the db.close() call inside the find query.
collection.find({}).toArray(function(err, docs) {
console.log(docs[0]);
db.close();
});

Error "Undefined is not a function " Using callback node.JS

I am trying to save a new Document (user) in my MongoDb and I use callback. The code runs and goes until save the user, but after that I get an error.So I can save user. I have the following code:
function saveUser(userName, socialMediaType, socialMediaID, setDocNumber, callback){
var user;
if(socialMediaType == "fbUID"){
user = new users({
userName: userName,
userEmail: 'userEmail',
teams:[],
fbUID : socialMediaID
});
}else
if(socialMediaType =="google"){
//do the same
}
var query = {}
query["'"+ socialMediaType +"'" ] = socialMediaID
users.findOne(query, function(err, userFound){
if (err) { // err in query
log.d("Error in query FoundUser", err)
log.d("User Found", userFound)
}else
if(userFound == undefined){ //if user does not exist
user.save(function(err, user){
if(err) return console.error(err);
log.d("user saved", user);
currentSession = sessionOBJ.login(user._id, socialMediaID);
callback(currentSession,"created")
});
}else{
currentSession = sessionOBJ.login(userFound._id, socialMediaID);
callback(currentSession,"logged")
}
});
}
I call the function above through this code:
f(fbUID !== undefined){
userModelOBJ.saveUser(userName,"fbUID", fbUID, function(currentSession, status) {
res.send({"status":status,
"sessionID": currentSession.sessionID,
"expires" : currentSession.date});
});
I am getting this error :
The error is in the line :
callback(currentSession,"created")
What could be the problem?
I already did many researchers but this is a specific case.
Your saveUser() call is missing the setDocNumber argument. It looks like you're not using it in your code though, so you might be able to safely remove it. If you are using it somewhere else (that you haven't shown) then you need to do some argument checking at the top of saveUser() to support optional arguments.

Resources