Created
July 14, 2011 15:22
-
-
Save justmoon/1082663 to your computer and use it in GitHub Desktop.
MongooseJS Binary Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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