I´m reading
learning nodejs book and this is a little example. It´s not the best solution, but it´s a piece of code.
var mongodb = require('mongodb');
var bugRepository = module.exports = {};
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true});
bugRepository.database = new mongodb.Db('bugdb', server);
var self = bugRepository;
bugRepository.insert = function(bug){
console.log('insert ' + bug);
self.database.collection('bugs', function(err, collection){
collection.insert([bug], {safe:true}, function(err, result){
if(err){
console.log('err saving new bug: ' + err);
return;
}
if(result){
console.log('result of saving bug: ' + result);
}
});
});
}
bugRepository.delete = function(bug){
console.log('delete id ' + bug.idBug);
self.database.collection('bugs', function(err, collection){
collection.remove({id: bug.idBug}, function(err, result){
if(err){
console.log('error removing one bug: ' + err);
return;
}
if(result){
console.log('deleting result: ' + result);
}
return result;
});
});
}
bugRepository.get = function(bug){
console.log('get id: ' + bug.idBug);
self.database.collection('bugs', function(err, collection){
collection.remove({id: bug.idBug}, function(err, doc){
if(err){
console.log('error removing one bug: ' + err);
return;
}
if(doc){
console.log('getting a bug' + doc);
return doc;
}
});
});
}
With the test:
var repository = require('./bugRepository');
var testCase = require('nodeunit').testCase;
module.exports = testCase({
//setup: function(){},
//teardown: function(){},
'Save simple bug': function(test){
var bug = {};
bug.idBug = 1;
bug.name = 'bug name';
bug.description = 'bug description';
repository.insert(bug);
var expected = repository.get(bug);
test.equal(bug, expected);
repository.delete(bug);
test.done();
}
});
for running the test:
nodejs /usr/local/bin/node_modules/nodeunit/bin/nodeunit bugRepository.test.js
No hay comentarios:
Publicar un comentario