Last active
December 24, 2015 08:18
-
-
Save jamlfy/6769185 to your computer and use it in GitHub Desktop.
Document watch!!!
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 see = require('mongose-watch'); | |
var Player = new Schema({ }); | |
var Game = new Schema({ }); | |
Player.plugin(watch() ); | |
var watchingPlayer = Plaver.findById( MyID ).watch( "_id" ); | |
watchingPlayer.start( function (err, doc){ | |
console.log("Player :"); | |
console.log(doc); | |
watchingPlayer.stop(function(){ | |
console.log('Close the watch!'); | |
}); | |
}); | |
var watchingGame = Plaver.find().watch( new Date() ); | |
watchingGame.start( function (err, games){ | |
console.log("Player :"); | |
console.log(games); | |
watchingGame.stop(); | |
}); | |
Plaver.find().watch( new Date(), function (start, stop){ | |
this.start(function(err, docs){ | |
console.log("Async :"); | |
console.lgg(docs); | |
stop(function(){ | |
console.log("Stop"); | |
}); | |
}); | |
}); | |
*/ | |
var Query = require('mongoose').Query; | |
var _ = require('underscore'); | |
module.exports = exports = function( label ){ | |
var self = { | |
label : label || "lastMod" , | |
field : {} | |
}; | |
Query.prototype.watch = function (){ | |
var sleft = {}; | |
for (var i = arguments.length - 1; i >= 0; i--) { | |
if( _.isString(arguments[i]) ) | |
sleft.label = arguments[i]; | |
if( _.isDate(arguments[i] ) ) | |
sleft.time = arguments[i]; | |
if( _.isFunction(arguments[i] ) ) | |
sleft.callback = arguments[i]; | |
} | |
sleft.label = sleft.label || self.label; | |
sleft.time = sleft.time || new Date(); | |
sleft.query = sleft.label === '_id' ? this : this.where( sleft.label ).gte( sleft.time ); | |
sleft.timer = null; | |
this.start = function ( times, cb ){ | |
if( !_.isFunction(times) && !_.isFunction( cb ) ) throw new Error('Is not a function'); | |
var callback = _.isFunction(times) ? times : cb; | |
sleft.timer = setInterval( function(){ | |
sleft.query.exec('find', callback); | |
}, _.isNumber(times) ? times : 350 ); | |
}; | |
this.stop = function ( cb ){ | |
clearInterval(sleft.timer); | |
sleft.timer = null; | |
if( _.isFunction(cb) ) return cb(); | |
}; | |
return sleft.callback ? sleft.callback( this.start, this.stop ) : { start : this.start, stop : this.stop }; | |
}; | |
return function watch (schema, options) { | |
self.field[ self.label ] = { | |
type : Date, | |
default : Date.now, | |
required : true | |
}; | |
schema.add(self.field); | |
schema.pre('save', function (next) { | |
this[ self.label ] = new Date(); | |
next(); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/alejonext/mongoose-watch