Created
July 10, 2012 03:12
-
-
Save ishiduca/3080730 to your computer and use it in GitHub Desktop.
mongooseやり直し #mongoose #MongoDB #Node.js
This file contains hidden or 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
"use strict" | |
var mongoose = require('mongoose') | |
, Schema = mongoose.Schema | |
, mongodb = 'mongodb://localhost' | |
, db_name = 'Test' | |
, db = [ mongodb, db_name ].join('/') | |
, collection = 'users' | |
, crypto = require('crypto') | |
, hash_key = 'bd3dcffe8e4523ca98e80f51f5ec85c18d57ea87' | |
; | |
function createHash (str) { | |
var hmac = crypto.createHmac('sha1', hash_key); | |
hmac.update(str); | |
return hmac.digest('hex'); | |
} | |
function Que () { this.q = []; } | |
(function (qp) { | |
qp.push = function (job) { | |
if (typeof job !== 'function') return; | |
this.q.push(job); | |
return this; | |
}; | |
qp.release = function (data) { | |
if (! this.q.length > 0) return; | |
var job = this.q.shift(); | |
job(data); | |
return this; | |
}; | |
})(Que.prototype); | |
var UsersModel = new Schema({ | |
_id : { type: String //Number | |
//, default: Date.now | |
, required: true | |
} | |
, name : { type: String | |
, trim: true | |
, match: /^\w{3,4}$/ | |
, required: true | |
} | |
, password : { type: String | |
, trim: true | |
, match: /^\w{4,8}$/ | |
, required: true | |
} | |
}); | |
mongoose.connect(db); | |
mongoose.model(collection, UsersModel); | |
var Users = mongoose.model(collection); | |
function save (name, password) { | |
var q = new Que; | |
q.push(function () { | |
Users.findOne({ name: name }, function (err, doc) { | |
if (err) return console.log(err); | |
if (doc && doc.name === name) | |
return console.log("have the same name already"); | |
var users = new Users; | |
users._id = createHash(name); | |
users.name = name; | |
users.password = password; | |
q.release(users); | |
}); | |
}).push(function (users) { | |
users.save(function (err) { | |
if (err) return console.log(err.toString()); | |
q.release(); | |
}); | |
}).push(function () { | |
Users.find({ name : name }, function (err, docs) { | |
if (err) return console.log(err.toString()); | |
console.log(docs); | |
}); | |
}).release() | |
; | |
} | |
('hoge Hog hugen huza 1234 123 01234 do-ha').split(" ").forEach(function (name) { | |
save(name, 'pass_w'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
どうだろう?