Mongodb find() return undefined - javascript

When ever I try to just use a simple find() for my mongodb it returns undefined.
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/local';
MongoClient.connect(url, function (err, db) {
db.collection('pokemon').find({ $search: { $text: 'Pikachu' } }).toArray(function(err, data){ console.log(data) })
});
EDIT:
Turns out I never created an index by putting
db.collection('pokemon').createIndex({Name: 'text'})
before all the code.

First of all, every time where you have:
function(err, data){ console.log(data) }
you should check errors:
function (err, data) {
if (err) {
console.log('Error:', err);
} else {
console.log('Data:', data);
}
}
Then you will probably see what's going on.
This is also true for the database connection itself - instead of:
MongoClient.connect(url, function (err, db) {
// use db here
});
you should handle errors:
MongoClient.connect(url, function (err, db) {
if (err) {
// handle errors
} else {
// use db here
}
});
If you don't handle errors then don't be surprised that you don't know why you don't get values.

Related

How to properly use nodejs soap

My code looks like this:
soap.createClient(url, function(err, client) {
if(err) {
res.status(500);
return res.send(err);
}
client.GetMemberPIN({pUserName: 'r'}, function(error, result) {
if(error) {
res.status(500);
return res.send(error)
}
return res.send(result);
});
});
I tried running it and it returns this error?
{
"code": "ECONNRESET"
}
I'd suggest testing a few things:
Make sure the url points to a valid WSDL document, e.g. https://www.crcind.com/csp/samples/SOAP.Demo.CLS?WSDL=1
Log which part of the process fails, e.g. the client creation, or the function call.
Here's a working example testing against a public server, this might help you to understand what could be going wrong with your code:
const soap = require('soap');
const url = 'https://www.crcind.com/csp/samples/SOAP.Demo.CLS?WSDL=1';
const args = { id: 1 };
soap.createClient(url, function(err, client) {
if (err) {
console.error("An error occurred creating client:", err);
return;
}
client.FindPerson(args, function(err, response) {
if (err) {
console.error("An error occurred calling client.FindPerson:", err);
return;
}
console.log("client.FindPerson: response:", response);
});
});

how to get the new value of document after updating each time in nodejs loop?

I'm trying to update collection many times in a loop but each time I get the value of oldRight not changed it gives the first value always.
I'm storing topics in mongodb using nested sets pattern.
for(let name of level1) {
console.log(name);
var parent = 'root';
getParentAndAddTopic(name, parent, function (err, topic) {
if (err) {
console.log(err);
}
var oldRight = topic.right;
console.log(oldRight);
db.topics.create({name: name, parent: 'root', left: oldRight, right: oldRight + 1}
, function (err, res) {
if (err) throw err;
});
db.topics.updateMany({right: {$gte: oldRight}}, {$inc: {right: 2}}
, function (err, res) {
if (err) throw err;
});
});
function getParentAndAddTopic(name, parent, callback) {
db.topics.find({name: 'root'}, function (err, topics) {
if (err) {
callback(err, null);
} else {
callback(null, topics[0]);
}
});
}
}
Working with the database is an asynchronous function, you can't do it in a normal loop. And change var to let, using var is a bad practice leading to many problems.

why mongodb in node express cannot set result to outside variable

So this question might be a javascript concept question. but I cannot figure out why
I retrieve data from mongodb however, I cannot define _res variable to become the result.
console.log(_res) will return undefined.
Does anyone know why? and how to make it work as it should be?
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm").find(query).toArray( function(err, result) {
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData
db.close();
res.render('index.ejs', {
vmData: vmData
});
});
});
console.log(_res)
});
Mongodb query is an asynchronous operation. The console statement is executed before the query has been processed.
You define _res outside which is undefined outside, so the same value is consoled outside.
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm")
.find(query)
.toArray((err, result){
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData
db.close();
console.log('Inside', _res) // <---Should give you correct result
res.render('index.ejs', {
vmData: vmData
});
});
});
console.log('Outside', _res);
});
The code is being executed asynchronously due to which when the console.log is executed the _res is undefined.
Try to execute your logic when the asyn methods are being executed.
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm").find(query).toArray( function(err, result) {
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData;
console.log(_res);
db.close();
res.render('index.ejs', {
vmData: vmData
});
});
});
});

ExpressJS re-query database after adding record to database

I'm new to expressJS and i'm wondering what is the best way to requery the database (mongo in my case) to get all the records after one is added.
exports.get = function (db) {
return function (req, res) {
var collection = db.get('notes');
collection.find({}, {}, function (e, docs) {
res.send(docs);
});
};
};
exports.create = function (db) {
return function (req, res) {
var title = req.body.title;
var note = req.body.note;
var collection = db.get('notes');
// Insert/update the note
collection.insert(
{
"title": title,
"note": note
},
function (err, doc) {
// If it failed, return error
if (err) {
res.send("There was a problem adding the information to the database. Error: "+err);
} else {
//res.redirect('/');
//res.json(db.get('notes'));
// WHAT IS THE BEST THING TO DO HERE TO GET ALL THE RECORDS INCLUDING THE ONE I'VE JUST ADDED?
exports.get(db);
}
}
);
}
};
I would replace
exports.get(db);
for
collection.find({}, {}, function (e, docs) {
res.send(docs);
});
The reason is that you are invoking this in the callback, AFTER the record has been inserted
Your exports.get function return a function, a kind of middleware I see.
Repplace
exports.get(db);
by
exports.get(db)();

How to wait for a response from a mongo findOne query in a node/express app before using the response in following control flow

I am new to node, and also JavaScript callbacks.
I am trying to check if an account exists in mongo and then 'save it' if it doesn't and return an error if it does.
I am currently trying to figure this out outside of my express app. This is what i have..
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
if(err) throw err;
var query = { name : "www.website.com"}
findOne(db, query, function (doc) {
if(doc) {
console.log('account exists');
} else {
console.log('good to go');
}
console.dir(doc);
});
});
var findOne = function (db, query, callback) {
db.collection('accounts').findOne(query, function (err, doc) {
if(err) throw err;
db.close();
callback();
});
}
with the console.dir(doc); above returning as undefined. How do I wait for the findOne to return before using the callback to console.log or save the account?
The reason you are getting undefined is because when you call your callback your are not passing it the doc. That line should look like callback(doc).
Here is an updated version of your code with a few suggestions:
MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
if(err) throw err;
var query = { name : "www.website.com"}
findOne(db, query, function (err, doc) {
if(err) {
// something went wrong
console.log(err);
return;
}
if(doc) {
console.log('account exists');
console.dir(doc);
} else {
console.log('good to go');
}
});
});
var findOne = function (db, query, callback) {
db.collection('accounts').findOne(query, function (err, doc) {
db.close();
if(err) {
// don't use throw when in async code
// the convention is to call your callback with the error
// as the first argument (notice that I added an argument
// to the definition of your callback above)
callback(err);
}
else {
// call your callback with no error and the data
callback(null, doc);
}
});
}

Categories

Resources