Code Monkey home page Code Monkey logo

mongoose-types's Introduction

mongoose-types - Useful types and type plugins for Mongoose

Types include:

  • Email
  • Url

Plugins include:

  • useTimestamps Adds createdAt and updatedAt date attributes that get auto-assigned to the most recent create/update timestamp.

Installation

npm install mongoose-types

Setup

To include all of the defined types:

var mongoose = require("mongoose");
var db = mongoose.createConnection("mongodb://localhost/sampledb");
var mongooseTypes = require("mongoose-types");
mongooseTypes.loadTypes(mongoose);

You can also specify that you only want to load and use a limited subset of the types provided:

var mongoose = require("mongoose");
var db = mongoose.createConnection("mongodb://localhost/sampledb");
var mongooseTypes = require("mongoose-types");
// Only load the email type
mongooseTypes.loadTypes(mongoose, "email");

Using the types

Once you are setup, you can begin to use the new types.

Email

var Email = mongoose.SchemaTypes.Email;
var UserSchema = new Schema({
  email: {
      work: Email
    , home: Email
  }
});

Url

var Url = mongoose.SchemaTypes.Url;
var VisitSchema = new Schema({
    url: Url
  , referer: Url
});

Using the plugins

The useTimestamps plugin

var mongoose = require("mongoose");
var db = mongoose.createConnection("mongodb://localhost/sampledb");
var mongooseTypes = require("mongoose-types")
  , useTimestamps = mongooseTypes.useTimestamps;
var UserSchema = new Schema({
    username: String
});
UserSchema.plugin(useTimestamps);
mongoose.model('User', UserSchema);
var User = db.model('User', UserSchema);

var user = new User({username: 'Prince'});
user.save(function (err) {
  console.log(user.createdAt); // Should be approximately now
  console.log(user.createdAt === user.updatedAt); // true

  // Wait 1 second and then update the user
  setTimeout( function () {
    user.username = 'Symbol';
    user.save( function (err) {
      console.log(user.updatedAt); // Should be approximately createdAt + 1 second
      console.log(user.createdAt < user.updatedAt); // true
    });
  }, 1000);
});

Tests

To run tests:

make test

Contributors

License

MIT License


Author

Brian Noguchi

mongoose-types's People

Contributors

bnoguchi avatar turbo87 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoose-types's Issues

Not able to validate emails within an array

U have a schema where the user has an array of emails. I want to validate that each of these items are valid/invalid. But there are not getting validated. Please see the mocha,should test code here:

require.paths.unshift('./node_modules');
require('should');
var assert = require('assert');

var mongoose = require('mongoose')
, Schema = mongoose.Schema
, mongooseTypes = require("mongoose-types")
, db = mongoose.createConnection(getMongoUrl());

mongooseTypes.loadTypes(mongoose);

var Email = mongoose.SchemaTypes.Email;

/* if we use the below code.. we get: CALL_NON_FUNCTION_AS_CONSTRUCTOR exception

var emailType = mongoose.SchemaTypes.Email;
var Email = new mongoose.Schema({
type: emailType,
unique: true,
required: true,
lowercase: true
});

*/

describe('Schema with just one email; Simple User with an invalid email', function(){
var UserSchema = new Schema({
email: Email
});
var User = db.model('User', UserSchema);
//User.remove({}, function (err) {});

describe('Save invalid email', function(){
it('should throw vaidation error', function(done){
var user = new User({email: 'asdf.com'});
user.save(function(err){
err.message.should.equal('Validation failed');
done();
});
})
})
});

describe('Schema with an ARRAY of emails; User with 1 or more invalid emails', function(){
var UserSchema2 = new Schema({
emails: [Email]
});
var User2 = db.model('User2', UserSchema2);

describe('Save invalid email', function(){
it('should throw vaidation error', function(done){
var user2 = new User2({emails: ["rrr"]});
user2.save(function(err){
console.log(err);
assert.exist(err);
assert.exist(err.message);
assert.equal(err.message, 'Validation failed');
done();
});
})
})
});

function getMongoUrl() {
if (process.env.VCAP_SERVICES) {
var env = JSON.parse(process.env.VCAP_SERVICES);
var obj = env['mongodb-1.8'][0]['credentials'];
}
else {
var obj = {
"hostname": "localhost",
"port": 27017,
"username": "",
"password": "",
"name": "",
"db": ""
}
}
obj.hostname = (obj.hostname || 'localhost');
obj.port = (obj.port || 27017);
obj.db = (obj.db || 'test');

if (obj.username && obj.password) {
    return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
} else {
    return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
}

}

//to run.. mocha <testfile.js>

Can't use mutable header APIs after sent.

Hi,

Thanks for writing this great plugin. I'm using it in several collections.

I'm also trying to use mongoose-types in a embedded document, but it does not work: The first sub-document is added without any problems but then I cannot add more sub-documents. I always get the following error:

http.js:543
throw new Error("Can't use mutable header APIs after sent.");

Here is the code:

//add tracker to account.

var Actor = mongoose.model('Actor');
function add_tracker(req, res, next) { 
    Actor.findById(req.params.id, function(err, actor) {
        if (err) {
            console.log(err);
        }
        var tracker_value = req.body.tracker.value;
        var tracker = { value: tracker_value };
        var trackers_size = actor.trackers.length;
        actor.trackers.push(tracker);
        actor.save(function(err){
            res.local("actor", actor);
            if (err) res.send({ error: err.message });
            var tracker = actor.trackers[trackers_size];
            res.partial('account/_tracker', { object: tracker }, function(err, html) {
              if (err) {
                  res.send({ error: err.message });
              } else {
                  res.send({ prepend: html, to: '#tracker_list' });
              }
            });
          })
    });
}

//database schema:

var mongoose = require('mongoose'), 
    mongooseTypes = require("mongoose-types"),
    useTimestamps = mongooseTypes.useTimestamps;

var Trackers = new Schema({
        value : String
 });
Trackers.plugin(useTimestamps);

var Actor = new Schema({
        , name     : String
        , trackers      : [Trackers]
});
mongoose.model('Actor', Actor);

If I remove mongoose-types from the embedded the error does not occur.

Thanks.
Best regards,
Migrate

Dependency to mongoose 1.0.0

Hi,
Currently mongoose is on release 0.0.5, but types are dependent on 1.0.0 and registered in npm registry. How can we use this ?

Schema types standards are well defined

Though there are a huge diversity and far too many redundant sources, the schema types are fairly well defined and some entities (standards orgs) present profiles that are generally accurate. Something that would import or retain all general schema types based on the rigid foreign definition and the various validation requirements, or are there tools already that fetch the remote definitions and translate to the necessary structure?

url regex is too restrictive

The url regex checks for ftp, http,https, however there are a lot more protocols out there, so it would be best to check for word only (2 or more chars). For example, chrome uses: chrome:/ which is used as the return url when doing the oauth2 dance from within a plugin.

Normalising URLs - removing www.

from the tests it seems that the URL normalisation removes the 'www.' from the beginning of the URL. A lot of websites will not work withut the www. prefix (primarily websites that aren't configured correctly but there are still a lot of them out there. Can the URL normalisation be turned off?

URLs getting butchered. :(

Tried using mongoose-types for URL matching, but it's butchering my URLs. Not particularly liking the edits it's doing. It keeps removing the port number and adding question marks to the end of every URL. >.>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.