I have a funny issue with Mongoose, one of MongoDB's ODMs.
I wanted to alias the mongoose.model method into simply Model. I even checked the alias :
exports = Model = mongoose.model;
console.log(Model === mongoose.model); // returns true
I already did this for mongoose.Schema and it worked seamlessly.
Now when I register a schema using the aliased Model variable :
Model('User', UserSchema);
I get the following error :
/node_modules/mongoose/lib/index.js:257
if (!this.modelSchemas[name]) {
^
TypeError: Cannot read property 'User' of undefined
at Mongoose.model (/node_modules/mongoose/lib/index.js:257:25)
at Object.<anonymous> (/app/models/user.js:20:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at controllers_path (/app.js:23:2)
at Array.forEach (native)
But if I use the normal form, I get absolutely no errors :
mongoose.model('User', UserSchema);
Mongoose.js ODM or am I missing something ?
When you call mongoose.model(...), the mongoose object is getting passed into the model function as this. When you call the function through your alias, this will be set to global instead of mongoose.
If you really wanted to do this you'd have to do something like:
var Model = mongoose.model.bind(mongoose);
That way, mongoose gets passed into the function no matter how you call Model.
Just to elaborate on @JohnnyHK answer:
var a = {
b:function(){
console.log(this.name)
},
name:"its a"
}
a.b() //logs "its a"
var c = a.b;
c(); //logs undefined
While calling c the invoking context is window or the global object.