MongoClient not returning data in cucumberjs test - javascript

I've taken this apart several different ways. The find happens after the remove, and the find never finds anything. If I comment out the this.accounts.remove... the find works. If I leave the remove line in there it doesn't. My understanding of cucumberjs, mongo client and node indicates that the find should work.
I've even tried moving the remove/find sequence into its own file, and it works there. It seems to be only when I'm running it in cucumber that the sequence fails. I suspect because of the way of cucumber loads the files, but I'm not sure.
Can someone help me figure out how to get this working?
World.js:
var db = new Db('FlashCards', new Server('localhost', 27017));
db.open(function(err, opened) {
if (err) {
console.log("error opening: ", err);
done(err);
}
db = opened;
});
var {
defineSupportCode
} = require('cucumber');
function CustomWorld() {
this.db = db;
this.accounts = db.collection('accounts');
hooks.js:
Before(function(result, done) {
//comment this out, and leave a done(), it works!!!!
this.accounts.remove(function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
})
});
user_steps.js:
Then('I will be registered', function(done) {
let world = this;
this.accounts.find({
username: world.user.username
}).toArray(
function(err, accounts) {
if (err) {
console.log("Error retrieveing data: ", err);
done(err);
}
console.log("Accounts found: ", accounts);
expect(accounts).to.be.ok;
expect(accounts.length).to.be.equal(1);
done();
});
});
Inovcation:
cucumber-js --compiler es6:babel-core/register

You are missing the item to be removed in the remove method. I am assuming the item to be removed is
this.accounts.remove(function(error, result){

You are missing one parameter to remove method. The parameter is query to remove. I am assuming, the remove query is {username: world.user.username}
var qry={username: world.user.username};
Please try with the following:
Before(function(result, done) { //comment this out, and leave a done(), it works!!!!
var qry={username: world.user.username};
this.accounts.remove(qry, function(error, result){
if( error) {
console.log("Error cleaning the database: ", error);
done(error);
}
done();
}) });

Related

Search in ldapjs

I am trying to use the search method of Ldap.js in my node.js code. Here is my code for the client side. It adds successfully a user, but searching for the newly added user does not yield any results. (The ldap server is running in a docker container from https://github.com/osixia/docker-openldap)
var ldap = require("ldapjs");
var assert = require("assert");
var client = ldap.createClient({
url: "ldap://localhost:389",
});
client.bind("cn=admin,dc=example,dc=org", "admin", function (err) {
assert.ifError(err);
let newUser = {
cn: "userId7",
userPassword: "password",
objectClass: "person",
sn: "efub",
};
// Here i successfully add this user "userId7"
client.add(
"cn=userId7,dc=example,dc=org",
newUser,
(err, response) => {
if (err) return console.log(err);
return response;
}
);
var options = {
filter: "(objectClass=*)",
scope: "sub",
};
// Now the search, it runs without error, but does never receive a searchEntry
client.search(
"cn=userId7,dc=example,dc=org",
options,
function (error, search) {
console.log("Searching.....");
client.on("searchEntry", function (entry) {
console.log("I found a result in searchEntry");
});
client.on("error", function (error) {
console.error("error: " + error.message);
});
client.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log("client disconnected");
}
});
}
);
});
client.on('error', function (err) {
if (err.syscall == "connect") {
console.log(err);
}
});
Also, if it helps, this is how the newly added user looks like when i display all users from ldap by running docker exec my-openldap-container ldapsearch -x -H ldap://localhost:389 -b dc=example,dc=org -D "cn=admin,dc=example,dc=org" -w admin
# userId7, example.org
dn: cn=userId7,dc=example,dc=org
cn: userId7
userPassword:: cGFzc3dvcmQ=
objectClass: person
sn: efub
Update: I can successfully search for the user "userId7" with the shell command: docker exec ldap-service ldapsearch -LLL -x -D "cn=admin,dc=example,dc=org" -w "admin" -b "cn=userId7,dc=example,dc=org" "(objectclass=*)". How can i make ldapJS also run this search successfully?
Update 2: I can also successfully search by using the frontend "phpLDAPadmin" as seen in the screenshots below:
So i solved it. The correct client.search code is:
client.search(
"cn=userId7,dc=example,dc=org",
options,
function (error, res) {
console.log("Searching.....");
res.on("searchEntry", function (entry) {
console.log("I found a result in searchEntry", JSON.stringify(entry.object));
});
res.on("error", function (error) {
console.error("error: " + error.message);
});
client.unbind(function (error) {
if (error) {
console.log(error.message);
} else {
console.log("client disconnected");
}
});
}
);
Inside function (error, res) { I listened for the events via client.on("searchEntry", instead of res.on("searchEntry", therefore missing the events from the search results. The root cause was a classic copy and paste error and changing the variable while misunderstanding the origin of the event.

SQLITE_MISUSE: bad parameter or other API misuse [duplicate]

I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:
Create a sqlite3 database and catch an error if the creation fails for any reason.
Here is what I've tried:
let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){
if(!err){
logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
} else {
logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
}
});
dbHandler[username] = dbCreate;
When I execute this, I get the following error:
"Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"
This call without callback works just fine.
var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
But in this, I will not know if I run into any errors while creating the Database.
Try this:
let userDB = new sqlite3.Database("./user1.db",
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
(err) => {
// do your thing
});
Example.
#Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and
check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
and in this case if database does not exist new database will be created with connection.
sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.
sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.
So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.|');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
And this is the 2nd way to connect with database (already answered by #Irvin).
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});

Trouble with callbacks, error catching and MongoDB

I've been working on an application which allows me to add companies to a database. Originally my code was pure spaghetti, so I wanted to modularize it properly. For this purpose, I added routes, a controller and a dao.
This is how my code looks right now
Routes
app.post('/loadcompanies', (req, res)=> {
companiesController.loadcompany(req.body, (results)=>{
console.log(results);
res.send(200, "working!");
})
})
Controller
module.exports.loadCompany = (body, callback)=>{
companiesDao.loadCompany(body, callback);
}
Dao
module.exports.loadCompany = (company, callback)=>{
MongoClient.connect(conexionString, (err, database) => {
if (err) console.log(err);
db = database;
console.log(company);
db.collection('companies').insert(company, (err, result)=>{
callback({message:"Succesfully loaded company", company:result});
});
})
}
My current concern is that working with errors when modularizing like this is confusing. I tried adding a try-catch method around the db insert and throwing and error if there is one, but that doesn't seem to work. Other things I've tried is returning the error in the callback, like this:
if (err) callback (err, null);
but I end up getting a "Can't set headers after they are sent." error.
How would you handle errors in this situation? For example, in the case that someone tries to add a duplicate entry in an unique element.
You should be able to simply do the error checking inside the callback for the insert function:
db.collection('companies').insert(company, (err, result)=>{
if (err) {
callback(err, null);
return;
}
callback(null, {message:"Succesfully loaded company", company:result});
});
If you get an error like you say, that's probably because the database is actually returning an error. You could also make your errors more specific, like:
module.exports.loadCompany = (company, callback)=>{
MongoClient.connect(conexionString, (err, database) => {
if (err) {
callback(new Error('Connection error: ' + err.Error());
return;
}
db = database;
console.log(company);
db.collection('companies').insert(company, (err, result)=>{
if (err) {
callback(new Error('Insertion error: ' + err.Error());
return;
}
callback(null, {message:"Succesfully loaded company", company:result});
});
})
Here is your loadCompany done in async / await format.
Notise there is no need for error checking, errors will propagate as expected up the promise chain.
Note I've also changed loadCompany to be an async function too, so to call it you can simply do var ret = await loadCompany(conpanyInfo)
module.exports.loadCompany = async (company)=>{
let db = await MongoClient.connect(conexionString);
console.log(company);
let result = await db.collection('companies').insert(company);
return {message:"Succesfully loaded company", company:result};
}

Mocha/Node.js/PostgreSQL integration testing

I have been trying to get this to work for days. I've looked around the internets and on StackOverflow. There are examples of how to test APIs using MongoDB and how to write Mocha tests that execute PSQL commands. That's not what I want.
I created a wrapper for pg, called db.js from the instructions in this SO question (note my comments in the calls to console.log():
pg = require("pg");
config = require("./../config.js");
module.exports = {
query: function(text, values, cb) {
console.log("I get to this in Mocha");
pg.connect(config.connectionString, function(err, client, done) {
console.log("I never get here");
if (err) return console.error("error connecting to postgres: ", err);
client.query(text, values, function(err, result) {
console.log("I most certainly never get here");
done();
cb(err, result);
})
});
}
}
With that, I can do the following:
$ node
$ var db = require ("./path/to/db.js");
$ db.query("insert into sometable(id, value) values(1, \"blah\")", {}, function (err, result) {
if (err) { console.error ("db errored out man"); }
console.log("no error...");
console.log(result);
});
Believe it or not, that works without a hitch!
What I can't do is the same thing in a mocha test (i.e., db.spec.js):
var db = require("./../../../Data/db.js");
// These tests assume you have run the scripts in the -SQL repo
describe("module: db", function() {
it("provides a wrapper for the execution of queries", function () {
db.query("insert into employer.profile \
(id, returncustomer, receiveupdates, name, email, password, active) \
values (4, true, true, 'someNameLol', 'ce#spam.org', 'change_me', true)", {},
function (err, stdout, stderr) {
console.log(err || "");
console.log(stdout || "");
console.log(stderr || "");
}
);
});
});
Help! I want to be able to write integration tests using my database connection. Are there components I'm missing? Required libraries?
This is all hand-rolled, I'm not using an IDE, because I want to understand how it's supposed to work by myself.
Thanks in advance.
You need to include the done parameter, and call it at the end of your test.
describe("module: db", function() {
it("provides a wrapper for the execution of queries", function (done) {
db.query("insert into employer.profile \
(id, returncustomer, receiveupdates, name, email, password, active) \
values (4, true, true, 'someNameLol', 'ce#spam.org', 'change_me', true)", {},
function (err, stdout, stderr) {
console.log(err || "");
console.log(stdout || "");
console.log(stderr || "");
done();
}
);
});
});

How to find a document by an field other than _id using mongo/mongoose

Background:
I must create or update an document based on post request that I have zero control over. I'm calling the function updateOrCreate()
Question:
How can I properly find a document by an field called nuid without using _id in mongo/mongoose
example payload:
curl -H "Content-Type: application/json" -X POST -d '{"participant":{"nuid":"98ASDF988SDF89SDF89989SDF9898"}}' http://localhost:9000/api/things
thing.controller:
exports.updateOrCreate = function(req, res) {
//Thing.findByNuid() will not work but it will explain what i'm trying to accomplish
/**
Thing.findByNuid(req.body.participant.nuid, function (err, thing) {
if (err) { return handleError(res, err); }
if(!thing) {
Thing.create(req.body.participant, function(err, thing) {
if(err) { return handleError(res, err); }
});
}
var updated = _.merge(thing, req.body.participant);
updated.save(function (err) {
if (err) { return handleError(res, err); }
});
});
**/
//this block will fetch all the things that have nuids but that seems really heavy and awful practice
Thing.find({'nuid':req.body.participant.nuid}, function(err, thing){
console.log(thing);
});
// This block is here to communicate this will create a new thing as expected.
Thing.create(req.body.participant, function(err, thing) {
if(err) { return handleError(res, err); }
});
}
Schema
var ThingSchema = new Schema({
nuid: String
});
UPDATE:
var query = {"nuid": req.body.participant.nuid};
var update = {nuid: 'heyyy'};
Thing.findOneAndUpdate(
query,
update,
{upsert: true},
function(err, thing){
console.log(thing, "thing");
console.log(err, "err");
}
);
I would use findOneAndUpdate first and then based on the result do an insert. findOneAndUpdate use mongoDB findAndModify command.
You should also look at new & upsert options of it which would create a document if not found.

Categories

Resources