Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you search other models with instance methods in Mongoose?

When do models receive their prototype?

I know that embedding is generally the answer here, but I have a special case.

If I call to another model in an instance's custom method, it seems to fail.

The error I'm getting:

Fish.find is not a function at model.UserSchema.methods.fishes

The Fish model is made into a model:

    // Require mongoose to create a model.
var mongoose = require('mongoose'),
    User     = require('./user.js');

// Create a schema of your model
var fishSchema = new mongoose.Schema({
  name:       String,
  category:   String,
  user:       { type: mongoose.Schema.Types.ObjectId, ref:'User' }
});

// Create the model using your schema.
var Fish = mongoose.model('Fish', fishSchema);

// Export the model of the Fish.
module.exports = Fish;

The User model calls to the Fish model within the fishes custom instance method:

var mongoose     = require('mongoose'),
    Schema       = mongoose.Schema,
    bcrypt       = require('bcrypt-nodejs'),
    Fish         = require('./fish');

//||||||||||||||||||||||||||--
// CREATE USER SCHEMA
//||||||||||||||||||||||||||--
var UserSchema   = new Schema({
  name:        { type: String, required: true },
  phoneNumber: {
                 type: String,
                 required: true,
                 index: { unique: true },
                 minlength: 7,
                 maxlength: 10
  },
  password:    { type: String, required: true, select: false }
});


// … some bcrypt stuff…

// Access user's fishes - THIS IS WHAT'S MESSING UP!!
UserSchema.methods.fishes = function(callback) {
  Fish.find({user: this._id}, function(err, fishes) {
    callback(err, fishes);
  });
};

module.exports = mongoose.model('User', UserSchema);

When I call .fishes() in my seeds, it claims that Fish.find is not a function.

Why!? Any help would be greatly appreciated!

like image 982
EARnagram Avatar asked Dec 14 '22 04:12

EARnagram


1 Answers

The issue is a circular import (fish.js requires user.js that requires fish.js, etc).

You can work around that by resolving the model class at runtime:

UserSchema.methods.fishes = function(callback) {
  mongoose.model('Fish').find({user: this._id}, function(err, fishes) {
    callback(err, fishes);
  });
};
like image 103
robertklep Avatar answered Dec 16 '22 17:12

robertklep