Skip to content
Browse files

Initial commit

  • Loading branch information...
0 parents commit 6f0d5465db3511a78847cfa49ec570f75d515793 @lowol committed with lowol Jul 16, 2012
Showing with 102 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +19 −0 README.md
  3. +29 −0 examples/index.js
  4. +34 −0 formatdate.js
  5. +19 −0 package.json
1 .gitignore
@@ -0,0 +1 @@
+node_modules
19 README.md
@@ -0,0 +1,19 @@
+mongoose-schema-formatdate
+==========================
+
+mongoose formatdate schema
+
+## Installation
+
+ $ npm install mongoose-schema-formatdate
+
+## Example
+
+[Example](https://github.com/lowol/mongoose-schema-formatdate/blob/master/examples/index.js)
+
+
+## License
+
+The MIT License
+
+
29 examples/index.js
@@ -0,0 +1,29 @@
+var mongoose = require('mongoose'),
+ FormatDate = require('../formatdate');
+
+/**
+ * example
+ */
+var db = mongoose.createConnection('mongodb://localhost/sample');
+
+var UserSchema = new mongoose.Schema({
+ username: String,
+ password: String,
+ date: {type: FormatDate, format: 'YYYY-MM-DD', default: Date.now}
+});
+var User = db.model('User', UserSchema);
+
+var user = new User({
+ username: 'foo',
+ password: 'bar',
+ date: "2012-07-07"
+});
+
+user.save(function(err, doc) {
+ console.log(err, doc);
+ User.find({}, function(err, docs) {
+ console.log(err, docs);
+ mongoose.disconnect();
+ process.exit();
+ });
+});
34 formatdate.js
@@ -0,0 +1,34 @@
+var mongoose = require('mongoose'),
+ SchemaTypes = mongoose.SchemaTypes,
+ CastError = mongoose.SchemaType.CastError;
+
+var moment = require('moment');
+
+/**
+ * FormatDate
+ */
+function FormatDate(path, options) {
+ SchemaTypes.Date.call(this, path, options);
+}
+FormatDate.prototype = Object.create(SchemaTypes.Date.prototype);
+FormatDate.prototype.cast = function(value) {
+ if (value instanceof Date) {
+ return value;
+ } else if (value instanceof Number ||
+ 'number' == typeof value ||
+ String(value) == Number(value)) {
+ // support for timestamps
+ return new Date(Number(value));
+ }
+
+ // format date string
+ var format = this.options.format || 'YYYY-MM-DD hh:mm:ss';
+ var mdate = moment(value.toString() || '', format);
+ if (mdate.format(format) != value) {
+ throw new CastError('date', value);
+ }
+
+ return mdate.toDate();
+};
+
+mongoose.Schema.Types.FormatDate = FormatDate;
19 package.json
@@ -0,0 +1,19 @@
+{
+ "name": "mongoose-schema-formatdate",
+ "version": "0.0.1",
+ "description": "mongoose formatdate schema",
+ "main": "formatdate.js",
+ "dependencies": {
+ "mongoose": "~2.7.1",
+ "moment": "*"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/lowol/mongoose-schema-formatdate.git"
+ },
+ "keywords": [
+ "mongoose"
+ ],
+ "author": "lowol",
+ "license": "MIT"
+}

0 comments on commit 6f0d546

Please sign in to comment.
Something went wrong with that request. Please try again.