2011-09-16 20 views
1

這是我locationsModel.js文件:爲什麼我的Mongoose模型不能加載?

var LocationSchema, LocationsSchema, ObjectId, Schema, mongoose; 
mongoose = require('mongoose'); 
Schema = mongoose.Schema; 
ObjectId = Schema.ObjectId; 
LocationSchema = { 
    latitude: String, 
    longitude: String, 
    locationText: String 
}; 
LocationsSchema = new Schema(LocationSchema); 
LocationsSchema.method({ 
    getLocation: function(callback) { 
    return console.log('hi'); 
    } 
}); 
exports.Locations = mongoose.model('Locations', LocationsSchema, 'locations'); 

在我的控制,我有:

var Locations, mongoose; 
mongoose = require('mongoose'); 
Locations = require('../models/locationsModel').Locations; 
exports.search = function(req, res) { 
    var itemText, locationText; 
    Locations.getLocation('info', function(err, callback) { 
    return console.log('calleback'); 
    }); 
    return; 
}; 

當我運行它,我得到以下錯誤:

TypeError: Object function model() { 
    Model.apply(this, arguments); 
    } has no method 'getLocation' 

我是什麼失蹤?

+0

在你的控制器,而不是'位置=需要( '../型號/ locationsModel')位置;'你可以簡單地去'Locations = mongoose.model('Locations')' –

回答

3

我認爲你所追求的是靜態而不是方法。

由於每docs

我想你應該定義getLocations功能如下(看你使用的getLocations你已經有了一個字符串參數以及回調:

LocationsSchema.statics.getLocation = function(param, callback) { 
    return console.log('hi'); 
} 

編輯:

staticsmethods之間的區別是您是否在該類型的「類型」或「對象」上調用它。 examples

BlogPostSchema.methods.findCreator = function (callback) { 
    return this.db.model('Person').findById(this.creator, callback); 
} 

,你會調用這樣:

BlogPost.findById(myId, function (err, post) { 
    if (!err) { 
    post.findCreator(function(err, person) { 
     // do something with the creator 
    } 
    } 
}); 
+0

非常感謝!哇,真棒!那麼,我什麼時候可以使用「靜態」與「方法」? – Shamoon

+0

@Shamoon:編輯我的答案。 – beny23

相關問題