Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define methods in a Mongoose model?

My locationsModel file:

mongoose = require 'mongoose' threeTaps = require '../modules/threeTaps'  Schema = mongoose.Schema ObjectId = Schema.ObjectId  LocationSchema =   latitude: String   longitude: String   locationText: String  Location = new Schema LocationSchema  Location.methods.testFunc = (callback) ->   console.log 'in test'   mongoose.model('Location', Location); 

To call it, I'm using:

myLocation.testFunc {locationText: locationText}, (err, results) -> 

But I get an error:

TypeError: Object function model() {     Model.apply(this, arguments);   } has no method 'testFunc' 
like image 741
Shamoon Avatar asked Sep 14 '11 16:09

Shamoon


People also ask

Can you define methods in a Mongoose schema?

Each Schema can define instance and static methods for its model.

What is method in Mongoose?

Mongoose provides 2 ways of doing this, methods and statics. Methods adds an instance method to documents whereas Statics adds static "class" methods to the Models itself. Given the example Animal Model below: var AnimalSchema = mongoose. Schema({ name: String, type: String, hasTail: Boolean }); module.

What is the difference between statics and methods in Mongoose?

Methods operate on an instance of a model. Statics behave as helper functions only and can perform any action you want, including collection level searching. They aren't tied to an instance of a Model. But methods are also defined on models and work on all the instances of that model.

What does populate method do Mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.


1 Answers

You didn't specify whether you were looking to define class or instance methods. Since others have covered instance methods, here's how you'd define a class/static method:

animalSchema.statics.findByName = function (name, cb) {     return this.find({          name: new RegExp(name, 'i')      }, cb); } 
like image 178
pdoherty926 Avatar answered Sep 18 '22 14:09

pdoherty926