From 976f1386d1660248a8bc0e2551030365afdb2b58 Mon Sep 17 00:00:00 2001 From: Nathan White Date: Wed, 12 May 2010 16:21:31 -0400 Subject: [PATCH] added support for ensuring indexes in model definitions, simple and compound indexes --- examples/models/User.js | 7 +++++++ examples/user.js | 1 - lib/model/index.js | 16 +++++++++++++++- lib/model/static.js | 1 + 4 files changed, 23 insertions(+), 2 deletions(-) diff --git a/examples/models/User.js b/examples/models/User.js index 67550eedb01..02042e2c597 100644 --- a/examples/models/User.js +++ b/examples/models/User.js @@ -12,6 +12,13 @@ Mongoose.Model.define('User', { age: Number } }, + + indexes : [ + 'username', + 'bio.age', + [['first'],['last']] + ], + setters: { first: function(v){ return v.toUpperCase(); diff --git a/examples/user.js b/examples/user.js index c5e35149b15..88e6f56792f 100644 --- a/examples/user.js +++ b/examples/user.js @@ -6,7 +6,6 @@ var sys = require('sys'), sys.puts(err); }); - // Mongoose.load(__dirname+'/../lib/model/plugins/behaviors.js'); Mongoose.load(__dirname+'/models/'); db = Mongoose.connect('mongodb://localhost/test'); diff --git a/lib/model/index.js b/lib/model/index.js index 788a2e25462..ecf784e244b 100644 --- a/lib/model/index.js +++ b/lib/model/index.js @@ -220,7 +220,7 @@ var object = require('../utils/object'), return this; } })(); - + model.name = collection; // collection = collection event loop... hmmm...FIXME addMethods(model,{ parent : parent, __meta__ : {type : {} } },false,model); @@ -256,6 +256,20 @@ var object = require('../utils/object'), store.collection(collection,function(aCollection){ model.collection = aCollection; model.loaded = true; + + model.indexInformation().execute(function(info){ + def.indexes.forEach(function(idx){ + var key = ''; + if(Object.prototype.toString.call(idx) === '[object Array]'){ + for(i=0,l=idx.length; i < l; i++){ + if(i) key += '_'; + key += idx[i][0] +'_1'; + } + } else key = idx + '_1'; + if(!info[key]) aCollection.createIndex(idx,function(){}); + }); + }); + model.dequeue(); }); } diff --git a/lib/model/static.js b/lib/model/static.js index c2170a99f04..60bf50e5c19 100644 --- a/lib/model/static.js +++ b/lib/model/static.js @@ -22,6 +22,7 @@ this.Static = { save : function(){ return this._cmd('save', Array.prototype.slice.call(arguments,0)); }, drop : function(fn){ return this.store.dropCollection(this.name, ((typeof fn == 'function') ? fn : function(){}) ); }, close : function(){ this.store.db.close(); }, + indexInformation : function(){ return this._cmd('indexInformation', Array.prototype.slice.call(arguments,0)); }, _cmd : function(cmd,args){ return new QueryPromise(cmd,args,this); },