Skip to content

Instantly share code, notes, and snippets.

@ishiduca
Created July 10, 2012 03:12
Show Gist options
  • Save ishiduca/3080730 to your computer and use it in GitHub Desktop.
Save ishiduca/3080730 to your computer and use it in GitHub Desktop.
mongooseやり直し #mongoose #MongoDB #Node.js
"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');
});
@ishiduca
Copy link
Author

どうだろう?

function Queue () {
    this.q = Array.prototype.slice.apply(arguments)
                 .filter(this.isFunction.bind(this));
    return this;
}
(function (qp) {
    qp.release = function (arg) {
        if (this.q.length > 0) {
            var job = this.q.shift();
            job(arg);
        }
        return this;
    };
    qp.push = function (job) {
        this.isFunction(job) && this.q.push(job);
        return this;
    };
    qp.isFunction (job) { return (typeof job === 'function'); };
})(Queue.prototype);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment