Skip to content

Instantly share code, notes, and snippets.

@justmoon
Created July 14, 2011 15:22
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justmoon/1082663 to your computer and use it in GitHub Desktop.
Save justmoon/1082663 to your computer and use it in GitHub Desktop.
MongooseJS Binary Example
var crypto = require('crypto');
var mongoose = require('./');
mongoose.connect('mongodb://localhost/bintest');
var Schema = mongoose.Schema;
var HashSchema = new Schema({
id : String
, hash : Buffer
});
mongoose.model('Hash', HashSchema);
var timeId = "test" + (new Date().getTime());
var testBuffer = new Buffer(crypto.createHash('sha256').update(new Buffer(0)).digest('binary'), 'binary');
var Hash = mongoose.model('Hash');
var sample = new Hash();
sample.id = timeId;
sample.hash = testBuffer;
sample.save(function (err) {
if (err) {
console.log(e.stack ? e.stack : e.toString());
process.exit(1);
}
Hash.findOne({id: timeId}, function (err, result) {
if (err) {
console.log(e.stack ? e.stack : e.toString());
process.exit(1);
}
if (testBuffer.length != result.hash.length) {
console.log('Incorrect length returned!');
process.exit(1);
}
for (var i = 0, l = testBuffer.length; i < l; i++) {
if (testBuffer[i] !== result.hash[i]) {
console.log('Buffer mismatch at pos ' + i);
process.exit(1);
}
}
console.log('SUCCESS!');
process.exit(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment