Skip to content

Instantly share code, notes, and snippets.

@uptownben
Created October 25, 2011 22:09
Show Gist options
  • Save uptownben/1314512 to your computer and use it in GitHub Desktop.
Save uptownben/1314512 to your computer and use it in GitHub Desktop.
Mongoose JS Schema methods error *SOLVED*
/**
* Module dependencies.
*/
var express = require('express');
var mongoose = require('mongoose');
var fs = require('fs');
var Schema = mongoose.Schema;
var db = mongoose.connect('mongodb://localhost/myapp');
// Schemas
var UserSchema = new Schema({
first_name:{type:String,required:true},
last_name:{type:String,required:true},
email:{type:String,required:true,index:{unique:true}},
loc:{lng:Number,lat:Number}
});
UserSchema.index({loc:'2d'});
UserSchema.method('findNearbyMatches',function(lng,lat,cb) {
//return this.find({loc:{$near:[lng,lat],$maxDistance:5}},cb); //<--- ERROR accessing "this", no find() method. SEE ERROR BELOW
return this.db.model('User').find({loc:{$near:[lng,lat],$maxDistance:5}},cb); //<--- must reference "find" this way...
});
// Set up models
var User = mongoose.model('User',UserSchema);
app.get('/localmatches/:lng/:lat',requireAuth,function(req,res){
var user = new User();
user.findNearbyMatches(req.params.lng,req.params.lat,function(err,users){
res.contentType('application/json');
var result = {status:'ok',message:'',users:users};
res.send(result);
})
});
/*
TypeError: Object #<model> has no method 'find'
at model.findNearbyMatches
*/
@uptownben
Copy link
Author

Ultimately I decided to make it a static so I wouldn't need to instantiate a new object every time I needed to call that particular function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment