Skip to content

Commit

Permalink
created helper function that extends json.parse to understand objecti…
Browse files Browse the repository at this point in the history
…ds and dates
  • Loading branch information
pmlopes committed Jul 3, 2012
1 parent 882c24e commit 7927e70
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 3 deletions.
2 changes: 2 additions & 0 deletions README.md
Expand Up @@ -14,6 +14,8 @@

## Methods

### ODM#parse

### Model#findOne
### Model#findById
### Model#find
Expand Down
29 changes: 27 additions & 2 deletions lib/index.js
Expand Up @@ -7,6 +7,9 @@ var Binary = mongodb.BSONPure.Binary;
var JSV = require("JSV").JSV;
var schema = JSV.createEnvironment("json-schema-draft-03");

var objectIdRegExp = /^[0-9a-fA-F]{24}$/;
var ISO8601RegExp = /^(\d{4})\D?(0[1-9]|1[0-2])\D?([12]\d|0[1-9]|3[01])(\D?([01]\d|2[0-3])\D?([0-5]\d)\D?([0-5]\d)?\D?(\d{3})?([zZ]|([\+\-])([01]\d|2[0-3])\D?([0-5]\d)?)?)?$/;

// lazy connector
var _collections = {};
var _connected = false;
Expand Down Expand Up @@ -255,7 +258,7 @@ var ODM = {
},

/**
* Schema validator
* Schema validator (JSV)
*/
schema: schema,

Expand All @@ -268,7 +271,29 @@ var ODM = {
*
* @return {Model}
*/
model: require('./model')
model: require('./model'),

/**
* Parses a JSON string to a JSON document. It is aware of ISO Dates and ObjectIds and coverts them on the fly.
*
* @param jsonString
* @return {Object} JSON
*/
parse: function (jsonString) {
return JSON.parse(jsonString, function (key, value) {
if (typeof value === 'string') {
// try to see if are receiving a string representation of an ObjectId
if (value.length === 24 && objectIdRegExp.test(value)) {
return ObjectID.createFromHexString(value);
}
// try to see if we are receiving an ISO string
if (ISO8601RegExp.test(value)) {
return new Date(Date.parse(value));
}
}
return value;
});
}
};

module.exports = ODM;
12 changes: 11 additions & 1 deletion lib/model.js
Expand Up @@ -76,8 +76,18 @@ module.exports = function (mongoCollection, schemaDef) {
/**
* @name Model
* @class Document Model Customized class for a mongodb document schema.
* @param {Object} [json] if provided will update the current instance with the json properties
*/
var Model = function () {
var Model = function (json) {
if (json !== undefined && json !== null) {
var key;
// update new ones
for (key in json) {
if (json.hasOwnProperty(key)) {
this[key] = json[key];
}
}
}
};

var odm = this;
Expand Down

0 comments on commit 7927e70

Please sign in to comment.